Skip to main content
 首页 » 编程设计

c#之使用 dotnetzip 库压缩流时文件损坏

2024年02月23日17lonelyxmas

文件已创建,大小似乎还可以,但双击时提示格式错误或文件已损坏。

这是我正在使用的代码

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); 
    } 
} 

有什么想法吗? 提前致谢!吉列尔莫。

请您参考如下方法:

我认为问题出在您的函数 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); 
  } 
} 

希望这对您有所帮助。