我已經研究了類似問題的答案,但還沒有看到將多個文件收集到一個ziparchive以供傳輸下載的答案。以下給出沒有錯誤,但不返回一個可識別的zip文件。將多個文件存入內存流的Ziparchive
public async Task<HttpResponseMessage> SendAZipOfFiles()
{
var memoryStream = new MemoryStream();
var response = new HttpResponseMessage(HttpStatusCode.OK);
List<string> filepaths = await GetSomeFiles();
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (string filepath in filepaths)
{
string filename = Path.GetFileName(filepath);
using (StreamReader reader = new StreamReader(filepath))
using (StreamWriter writer = new StreamWriter(archive.CreateEntry(filename).Open()))
{
writer.Write(reader.ReadToEnd());
}
}
}
memoryStream.Position = 0;
response.Content = new StreamContent(memoryStream);
response.Content.Headers.ContentLength = memoryStream.Length;
response.Content.Headers.ContentDisposition = new ContentDispositionHeaderValue("attachment")
{
FileName = "TheFile.zip")
};
response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/zip");
return response;
}
側面說明,但是當你打出來的荏苒部分作爲單獨的方法變得更容易了很多(單元測試。 –