Reputation: 1113
I have the following web controller:
List<string> output = new List<string>();
output.Add("line1");
output.Add("line2");
output.Add("line3");
output.Add("line4");
using (var memorystream = new MemoryStream())
{
using (var archive = new ZipArchive(memorystream, ZipArchiveMode.Create, true))
{
var fileInArchive = archive.CreateEntry("entry1");
using (var entryStream = fileInArchive.Open())
using (var streamWriter = new StreamWriter(entryStream))
{
output.ForEach(streamWriter.WriteLine);
}
}
memorystream.Seek(0, SeekOrigin.Begin);
var result = new HttpResponseMessage(HttpStatusCode.OK)
{
Content = new ByteArrayContent(memorystream.GetBuffer())
};
result.Content.Headers.ContentDisposition =
new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment")
{
FileName = "test.zip"
};
result.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return result;
}
On the receiving end i have a c# web form that access the controller this way:
var responsebody = response.Content.ReadAsByteArrayAsync().Result;
string filename = "test.zip";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.AppendHeader(
"content-disposition", string.Format("attachment; filename={0}", filename));
HttpContext.Current.Response.ContentType = "application/zip";
HttpContext.Current.Response.BinaryWrite(responsebody.ToArray());
But I just get an array of bytes in the reponsebody var. How can I convert this back to the original type, which is a ziparchive, or just another binary file to have it more generic?
Upvotes: 4
Views: 2428
Reputation: 149656
How can I convert this back to the original type, which is a
ZipArchive
?
You sent back the byte[]
as the response. That means, that on the receiving end, you'll have to exactly reverse that same process. Meaning, you take the byte array and put it into a ZipArchive
, and start reading:
var bytes = await response.Content.ReadAsByteArrayAsync();
using (var zippedBytesStream = new MemoryStream(bytes))
using (var archive = new ZipArchive(zippedBytesStream, ZipArchiveMode.Read, true))
{
foreach (ZipEntry entry in archive.Entries)
{
// Do stuff with entry.
}
}
Upvotes: 1