Frage

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.

War es hilfreich?

Lösung

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();
Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top