如何压缩大文件 C#

Mis*_*ssy 3 c# compression

我正在使用这种方法来压缩文件,它工作得很好,直到我得到一个 2.4 GB 的文件,然后它给了我一个溢出错误:

 void CompressThis (string inFile, string compressedFileName)
 {

        FileStream sourceFile = File.OpenRead(inFile);
        FileStream destinationFile = File.Create(compressedFileName);


        byte[] buffer = new byte[sourceFile.Length];
        sourceFile.Read(buffer, 0, buffer.Length);

        using (GZipStream output = new GZipStream(destinationFile,
            CompressionMode.Compress))
        {
            output.Write(buffer, 0, buffer.Length);
        }

        // Close the files.
        sourceFile.Close();
        destinationFile.Close();
  }
Run Code Online (Sandbox Code Playgroud)

我可以做什么来压缩大文件?

Vad*_*nov 7

您不应该将整个文件写入内存。使用Stream.CopyTo来代替。此方法从当前流中读取字节,并使用指定的缓冲区大小(默认为 81920 字节)将它们写入另一个流。

Stream如果使用using关键字,您也不需要关闭对象。

void CompressThis (string inFile, string compressedFileName)
{
    using (FileStream sourceFile = File.OpenRead(inFile))
    using (FileStream destinationFile = File.Create(compressedFileName))
    using (GZipStream output = new GZipStream(destinationFile, CompressionMode.Compress))
    {
        sourceFile.CopyTo(output);
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以在MSDN上找到更完整的示例。