1

文件已创建,大小似乎还可以,但是当我双击它时,它说它的格式错误或文件已损坏。

这是我正在使用的代码

public MemoryStream CompressFiles(Dictionary<string, MemoryStream> filesToBeCompressed)
{
    var output = new MemoryStream();
    using (var zip = new ZipFile())
    {
        foreach (var entry in filesToBeCompressed)
        {
            entry.Value.Seek(0, SeekOrigin.Begin); // <-- must do this after writing the stream (I've read this in a blog
            zip.AddEntry(entry.Key.Substring(entry.Key.LastIndexOf('/') + 1, entry.Key.Length - entry.Key.LastIndexOf('/') - 1), entry.Value);
            zip.Save(output);
        }
    }
    return output;
}

然后在调用方法中

SaveStreamToFile(documentCompressedName,getDocument());

getDocument() 在内部调用 Compress

最后那个方法

private static void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Fill the bytes[] array with the stream data
        var bytesInStream = new byte[stream.Length];
        stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

        // Use FileStream object to write to the specified file
        fileStream.Write(bytesInStream, 0, bytesInStream.Length);
    }
}

有任何想法吗?提前致谢!吉列尔莫。

4

2 回答 2

3

我认为问题出在你的功能SaveStreamToFile上。在将存档写入磁盘之前,您必须将流的位置设置为开头:

private static void SaveStreamToFile(string fileFullPath, Stream stream)
{
  if (stream.Length == 0) return;

  // Set the position within the stream to the beginning of the stream
  stream.Seek(0, SeekOrigin.Begin);      

  // Create a FileStream object to write a stream to a file
  using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
  {
    // Fill the bytes[] array with the stream data
    var bytesInStream = new byte[stream.Length];
    stream.Read(bytesInStream, 0, (int)bytesInStream.Length);

    // Use FileStream object to write to the specified file
    fileStream.Write(bytesInStream, 0, bytesInStream.Length);
  }
}

希望这可以帮助。

于 2011-10-05T19:34:46.387 回答
1

从您的代码片段中,我的猜测是,Position当您将 MemoryStream 传递给时,它位于流的末尾SaveStreamToFile,并且由于您从未将位置设置回流的开头,因此您stream.Read实际上根本没有读取任何字节。如果您使用十六进制编辑器打开您的输出 zip 文件,您可能会看到它全是零。

您在这里有很多选择,但我的建议是尝试:

private static void SaveStreamToFile(string fileFullPath, Stream stream)
{
    if (stream.Length == 0) return;

    // Create a FileStream object to write a stream to a file
    using (FileStream fileStream = System.IO.File.Create(fileFullPath, (int)stream.Length))
    {
        // Use FileStream object to write to the specified file
        fileStream.Write(stream.GetBuffer(), 0, stream.Length);
    }
}

这种方法可以避免复制MemoryStream. 虽然我不知道您的 zip 文件有多大,因此在内存使用方面可能不是问题,但将 zip 文件存储在内存中两次 - 一次MemoryStreambytesInStream.

于 2011-10-05T19:35:31.607 回答