我有以下网络控制器:
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;
}
在接收端,我有一个c#web表单,以这种方式访问控制器:
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());
但我只是在reponsebody var中得到一个字节数组。我怎样才能将它转换回原始类型,这是一个ziparchive,或者只是另一个二进制文件,以使它更通用?
答案 0 :(得分:1)
如何将其转换回原始类型,即
ZipArchive
?
您已将byte[]
作为回复发回。这意味着,在接收端,您必须完全扭转相同的过程。这意味着,您将字节数组放入ZipArchive
,并开始阅读:
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.
}
}