【发布时间】:2017-09-21 19:03:14
【问题描述】:
我有一个托管大型 XML 文件存档的服务器,并且一个 API 在 zip 中检索请求的文件。如果我选择大约 11 个或更少的文件,则 zip 会很好地返回。如果我检索更多内容,我会在尝试打开 zip 时收到以下错误:
"Windows 无法打开该文件夹。压缩 (zipped) 文件夹是 无效。”
以下是创建 zip 的数据类和方法:
//Archive file containing filename and content as memory stream
public class ArchiveFile {
public string FileName;
public System.IO.MemoryStream FileContent;
}
//Method to retrieve archive files and zip them
public static System.IO.MemoryStream GetFilesAsZip (string[] arrFileNames) {
MemoryStream zipStream = null;
using (zipStream = new MemoryStream()) {
// Retrieve files using above method
ArchiveFile[] retrievedFiles = GetFilesFromArchive(arrFileNames);
// Initialize new ZipArchive on the return object's MemoryStream property
using (ZipArchive archive = new ZipArchive(zipStream, ZipArchiveMode.Update, leaveOpen: true)) {
// Write file entries into archive
foreach (ArchiveFile dataFile in retrievedFiles) {
if (dataFile.FileContent != null) {
// Create new ZipArchiveEntry with content
ZipArchiveEntry zipEntry = archive.CreateEntry(dataFile.FileName);
dataFile.FileContent.WriteTo(zipEntry.Open());
}//end if
} // end foreach
} //end using
} //end using
return zipStream;
}//end method
//API to return content to user as an MVC File Content Result
[HttpGet]
public ActionResult DownloadFiles (string [] fileNames) {
FileContentResult data = new FileContentResult(GetFiles(fileNames).GetBuffer(), “application/zip”) { FileDownloadName = “files.zip” };
return data;
} //end method
写入内存流时,损坏可能与空间分配有关。我注意到我所有“成功”的 zip(11 个或更少的文件)的大小为 259 KB,但所有“不成功的”zip(超过 11 个文件)的大小为 517 KB,一些较大的尝试 zip 大小为 1034 KB。这些都是 258.5 KB 的倍数,这让我觉得太巧合了,特别是因为 11 个文件的 zip 会产生 259 KB 的 zip,但 12 个文件的 zip 会产生 517 KB 的 zip。
对它可能是什么有任何见解?
【问题讨论】:
-
您能以某种方式共享 XML 文件吗?
-
很遗憾我不能,它们包含私人信息。
-
您没有正确使用 MemoryStream。而不是在使用之外新建 MemoryStream,新建一个字节数组并返回它。它的 zipStream.ToArray()
-
@Aaron.S 你介意扩展一下你的意思吗?
-
我会重构你的代码,等等。您是否将有问题的文件发送到控制器,然后返回一个 zip 文件?还是只是文件名及其在服务器上的位置?
标签: c# asp.net asp.net-mvc zip