问题
I am using ZipArchive to create a zipped folder for a list of documents.
I cant figure out why, when I return my archived folder it is empty.
Does anyone see what I am doing wrong here?
My code is as follows:
if (files.Count > 1)
{
var ms = new MemoryStream();
var zipArchive = new ZipArchive(ms, ZipArchiveMode.Create, false);
foreach (var file in files)
{
var entry = zipArchive.CreateEntry(file.UploadFileName, CompressionLevel.Fastest);
using (var streamWriter = new StreamWriter(entry.Open()))
{
Stream strFile = new MemoryStream(file.UploadFileBytesStream);
streamWriter.Write(strFile);
strFile.CopyTo(ms);
}
}
return File(ms, System.Net.Mime.MediaTypeNames.Application.Zip, "FinancialActivityReports.zip");
}
回答1:
Assuming the following model for file
public class FileModel {
public string UploadFileName { get; set; }
public byte[] UploadFileBytesStream { get; set; }
}
The following helper was written to create the stream of the compressed files
public static class FileModelCompression {
public static Stream Compress(this IEnumerable<FileModel> files) {
if (files.Any()) {
var ms = new MemoryStream();
var archive = new ZipArchive(ms, ZipArchiveMode.Create, false);
foreach (var file in files) {
var entry = archive.add(file);
}
ms.Position = 0;
return ms;
}
return null;
}
private static ZipArchiveEntry add(this ZipArchive archive, FileModel file) {
var entry = archive.CreateEntry(file.UploadFileName, CompressionLevel.Fastest);
using (var stream = entry.Open()) {
stream.Write(file.UploadFileBytesStream, 0, file.UploadFileBytesStream.Length);
stream.Position = 0;
stream.Close();
}
return entry;
}
}
You code, assuming files
is derived from IEnumerable<FileModel>
will then change to this...
if (files.Count > 1)
{
var stream = files.Compress();
return File(stream, System.Net.Mime.MediaTypeNames.Application.Zip, "FinancialActivityReports.zip");
}
来源:https://stackoverflow.com/questions/36776704/ziparchive-returning-empty-folder-c-sharp