【问题标题】:out of memory exception in compress large files using io.compression使用 io.compression 压缩大文件时出现内存不足异常
【发布时间】:2015-09-13 10:05:25
【问题描述】:

我试图不超过内存最大大小,所以我必须每次检查它是否大于最大内存大小然后我将它刷新到 zip 文件 Stream 中。问题在这里它用文件流中存在的内存流替换内存流,或者有没有办法用另一种方式做同样的事情(但不使用任何 DLL Lib)

MemoryStream memoryStream = new MemoryStream();
   FileStream fileStream = new FileStream(sbZipFolderName.ToString(),FileMode.Create);
   foreach (FileInfo flInfo in ListfileFolderPaths)
    {
      using (var archive = new ZipArchive(memoryStream, ZipArchiveMode.Update, true))          
      archive.CreateEntryFromFile(flInfo.FullName, slastFolderName + "/" + flInfo.DirectoryName.Replace(new DirectoryInfo(sFolderPath.ToString()).FullName, "") + "/" + flInfo.Name);
      if (memoryStream.Length > MaxSize)
      {
    using (fileStream = new FileStream(sFolderPath + "/" + slastFolderName + ".zip",     FileMode.Create))
         {
             memoryStream.Seek(0, SeekOrigin.Begin);
             memoryStream.CopyTo(fileStream);
             memoryStream = new MemoryStream();

           }
      }
   }
   if ((memoryStream != null) && (memoryStream.Length > 0))
      memoryStream.CopyTo(fileStream);

【问题讨论】:

  • 为什么要使用MemoryStream?只需在FileStream 上打开您的ZipArchive
  • 谢谢你的回复,有没有例子说明如何做到这一点
  • 没什么可给的 - new ZipArchive(fileStream, ... 并删除所有与 MemoryStream 相关的代码。

标签: c# asp.net exception


【解决方案1】:

您可以使用Gzip 存档来压缩文件。

这是压缩:

public static byte[] Compress(byte[] raw)
{
using (MemoryStream memory = new MemoryStream())
{
    using (GZipStream gzip = new GZipStream(memory,
    CompressionMode.Compress, true))
    {
    gzip.Write(raw, 0, raw.Length);
    }
    return memory.ToArray();
   }
  }
}

这个要解压:

 static byte[] Decompress(byte[] gzip)
{
// Create a GZIP stream with decompression mode.
// ... Then create a buffer and write into while reading from the GZIP stream.
using (GZipStream stream = new GZipStream(new MemoryStream(gzip), CompressionMode.Decompress))
{
    const int size = 4096;
    byte[] buffer = new byte[size];
    using (MemoryStream memory = new MemoryStream())
    {
    int count = 0;
    do
    {
        count = stream.Read(buffer, 0, size);
        if (count > 0)
        {
        memory.Write(buffer, 0, count);
        }
    }
    while (count > 0);
    return memory.ToArray();
    }
}
}

}

告诉我它是否有效。

祝你好运。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-30
    • 2015-02-19
    • 1970-01-01
    • 2011-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多