3

我正在以胜利形式工作。执行以下操作时出错。System.OutOfMemoryException当我尝试连续运行大约 2-3 次操作时,它会显示错误。似乎.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());
}
4

3 回答 3

7

替换ReadAllBytesStream.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);
    }
}
于 2012-08-27T13:43:27.880 回答
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 字节的块。

于 2012-08-27T13:43:33.797 回答
1

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

    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);
}
于 2012-08-27T13:44:04.623 回答