使用ASP.NET,我怎样才能从一个字符串数组中创建一个压缩文件?[英] Using ASP.NET how can I create a zip file from an array of strings?

本文是小编为大家收集整理的关于使用ASP.NET,我怎样才能从一个字符串数组中创建一个压缩文件?的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

本文来自:IT宝库(https://www.itbaoku.cn)

我正在使用ASP.NET,我更喜欢VB作为语言,但是我应该能够为我的需要翻译C#.

我有一系列字符串,我想将其作为单个文件发送到浏览器以供用户保存.在搜索Internet时,将多个文件发送到浏览器的最常见解决方案是将它们汇总到浏览器中,并发送一个zip文件.

为此,我需要学习一些我不知道的东西;

1)我可以使用哪些工具/方法(最好是在IIS7上运行的ASP.NET内置)来创建ZIP FILESTREAM发送到浏览器?

2)我如何欺骗邮政编码,以为它从内存中的字符串中获取多个文件?我假设我需要创建文件流,但是我该如何分辨方法是什么是文件名,等等?

如果有一个类似于我需要的事情的示例,那将是很棒的.只是指我.

感谢您的帮助.

推荐答案

该方法可能是:

  1. 将字符串转换为流
  2. 将来自该流的数据添加到zip文件
  3. 将zip文件写入响应流

代码示例下面:

ZipFile zipFile = new ZipFile();
int fileNumber = 1;

foreach(string str in strArray)
{
    // convert string to stream
    byte[] byteArray = Encoding.UTF8.GetBytes(contents);
    MemoryStream stream = new MemoryStream(byteArray);

    stream.Seek(0, SeekOrigin.Begin);

    //add the string into zip file with a name
    zipFile.AddEntry("String" + fileNumber.ToString() + ".txt", "", stream);
}

Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=strings.zip");

zipFile.Save(Response.OutputStream);
zipFile.Dispose();

本文地址:https://www.itbaoku.cn/post/2354849.html

问题描述

I am using ASP.NET and I prefer VB as the language, but I should be able to translate C# for my needs.

I have an array of strings which I would like to send to the browser as individual files for the user to save. In searching the internet, the most common solution to send multiple files to a browser is to zip them up, and send a single zip file.

Towards that end, I need to learn a few things I do not know;

1) What tool/methods (preferably built in to ASP.NET running on IIS7) can I use to create a zip filestream to send to a browser?

2) How do I fool the zip tool into thinking it is getting multiple files from strings in memory? I assume I need to create filestreams, but how do I tell the methods what the file name is, etc.?

If there is an example of doing something substantially similar to what I need available, that would be great. Just point me at it.

Thanks for the help.

推荐答案

The approach could be:

  1. Convert the string into stream
  2. Add data from that stream into the zip file
  3. Write the zip file into response stream

Code example below:

ZipFile zipFile = new ZipFile();
int fileNumber = 1;

foreach(string str in strArray)
{
    // convert string to stream
    byte[] byteArray = Encoding.UTF8.GetBytes(contents);
    MemoryStream stream = new MemoryStream(byteArray);

    stream.Seek(0, SeekOrigin.Begin);

    //add the string into zip file with a name
    zipFile.AddEntry("String" + fileNumber.ToString() + ".txt", "", stream);
}

Response.ClearContent();
Response.ClearHeaders();
Response.AppendHeader("content-disposition", "attachment; filename=strings.zip");

zipFile.Save(Response.OutputStream);
zipFile.Dispose();