0

Im currently sending an XML file as a response without writing to my servers file system like so:

string xml = "my xml string"
string filename = "myFileName"

Response.Clear();
Response.ContentType = "text/xml";
Response.AddHeader("Content-Disposition", string.Format("attachment; filename={0}.xml", filename));
Response.Write(xml);
Response.End();

However I now need to return multiple XML files, I know that I may need to return a zip file as returning multiple files is not possible. Is it possible to write the xml files to a zip file without saving them to my servers file system? If not can I send multiple responses somehow?

user3839756
  • 793
  • 1
  • 9
  • 22
  • You can only return a single file per response. However, you can pack them into a `.zip` file, as shown here: http://stackoverflow.com/a/840815 – Xiaoy312 Apr 13 '17 at 19:19

1 Answers1

1

Here's one possible method. (Sorry, forgot to post a link to the library required. Ionic.Zip I believe it is part of the DotNetZip package, and is available through Nuget.)

Response.ContentType = "application/zip";
Response.AppendHeader("content-disposition", "attachment; filename=\"Download.zip\"");
using (ZipOutputStream zOut = new ZipOutputStream(HttpContext.Current.Response.OutputStream))
{
    FileInfo f1 = new FileInfo(fileName1);
    zOut.PutNextEntry(f1.Name);
    using (var input = f1.OpenRead())
    {
        byte[] buffer = new byte[2048];
        int n;
        while ((n = input.Read(buffer, 0, buffer.Length)) > 0)
        {
            zOut.Write(buffer, 0, n);
        }
    }
}
Chris Berger
  • 557
  • 4
  • 14