执行GZipStream压缩时抛出System.OutofMemoryException

时间:2012-08-27 13:35:26

标签: c# .net out-of-memory gzipstream

我正在以胜利形式工作。执行以下操作时出错。 当我尝试连续运行2-3次操作时,它显示System.OutOfMemoryException错误。似乎.NET无法释放运行中使用的资源。我用于操作的文件很大,大约超过500 MB。

我的示例代码如下。请帮我解决错误。

try
{
   using (FileStream target = new FileStream(strCompressedFileName, FileMode.Create, FileAccess.Write))
   using (GZipStream alg = new GZipStream(target, CompressionMode.Compress))
   {
       byte[] data = File.ReadAllBytes(strFileToBeCompressed);
       alg.Write(data, 0, data.Length);
       alg.Flush();
       data = null;
    }
}
catch (Exception ex)
{
    MessageBox.Show(ex.ToString());
}

3 个答案:

答案 0 :(得分:7)

ReadAllBytes替换为Stream.CopyTo

using (FileStream target = new FileStream(strCompressedFileName, FileMode.Create, FileAccess.Write))
using (GZipStream alg = new GZipStream(target, CompressionMode.Compress))
{
    using (var fileToRead = File.Open(.....))
    {
        fileToRead.CopyTo(alg);
    }
}

答案 1 :(得分:6)

一个非常粗略的例子可能是

// destFile - FileStream for destinationFile 
// srcFile - FileStream of sourceFile
using (GZipStream gz = new GZipStream(destFile, CompressionMode.Compress))
{
     byte[] src = new byte[1024];
     int count = sourceFile.Read(src, 0, 1024);
     while (count != 0)
     {
         gz.Write(src, 0, count );
         count = sourceFile.Read(src, 0, 1024);
     }
}
// flush, close, dispose ..

所以基本上我将你的ReadAllBytes改为只读了1024个字节的块。

答案 2 :(得分:0)

您可以尝试使用此方法压缩文件MSDN link

    public static void Compress(FileInfo fileToCompress)
    {
        using (FileStream originalFileStream = fileToCompress.OpenRead())
        {
            using (FileStream compressedFileStream = File.Create(fileToCompress.FullName + ".gz"))
            {
               using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
               {
                      originalFileStream.CopyTo(compressionStream);                                
               }
            }
        }
    }

用法:

string directoryPath = @"c:\users\public\reports";

DirectoryInfo directorySelected = new DirectoryInfo(directoryPath);

foreach (FileInfo fileToCompress in directorySelected.GetFiles())
{
    Compress(fileToCompress);
}