【发布时间】:2015-08-19 20:06:40
【问题描述】:
以下例程来自 Web API 中的文件服务类。该例程的目的是接收文件路径列表并将 zip 文件作为字节数组返回。 (调用此例程的例程将处理将文件传递给用户。)此例程使用来自System.IO.Compression 的ZipArchive 类。
此例程生成的文件已损坏。返回值的大小始终为 1024 字节。
此代码与我在 MSDN 和 Stack Overflow 上找到的示例几乎相同。它有什么不正确的?
public byte[] RetrieveMultipleFilesAsZip(IEnumerable<string> relativePaths)
{
using (var memoryStream = new MemoryStream())
{
using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Create, true))
{
foreach (var path in relativePaths)
{
try
{
// ActualPath(): Get the actual path where the file actually lives.
var actualPath = ActualPath(path);
var filename = Path.GetFileName(actualPath);
if (filename == null) continue;
var archiveEntry = archive.CreateEntry(filename);
using (var writer = new StreamWriter(archiveEntry.Open()))
{
// RetrieveFile(): A routine in this class that gets the contents of each file.
writer.Write(RetrieveFile(path));
}
}
catch (Exception ex)
{
// ignore this
}
}
}
memoryStream.Seek(0, SeekOrigin.Begin);
return memoryStream.GetBuffer();
}
}
【问题讨论】:
-
跟踪代码,似乎只有文件的条目被写入流,而不是文件的内容。给定 6 个不同大小的文件,
using archive块内只写入了大约 350 个字节。在退出using archive块时,又写入了 400 个字节。