【问题标题】:Best way to compress (ie best combo of compression ratio and speed) a directory of large files (each one b/w 100-300 MB) in C#?在 C# 中压缩大文件目录(每个 100-300 MB)的最佳方法(即压缩比和速度的最佳组合)?
【发布时间】:2011-11-11 21:39:24
【问题描述】:

我正在编写一个控制台应用程序来压缩一个包含大文件(大约 30 个)的目录,每个文件大约 100-300 MB,这将每天执行一次(随着新文件的进入)。我尝试使用内置的 GZipStream 类,每个文件大约需要 15 秒,压缩比约为 0.212。我想知道第三方库是否有更有效的方法,或者是否有某种方法可以提高压缩率。最后,线程是加快这个过程的一个选项吗?

这是我目前使用的代码(基本上来自 GZipStream 上的 MSDN 文章)

private void CompressFile(FileInfo fileInfo)
{
    // Get the stream of the source file.
    using (FileStream inFile = fileInfo.OpenRead())
    {
        Timer.Reset();

        // Prevent compressing hidden and 
        // already compressed files.
        if ((File.GetAttributes(fileInfo.FullName) & FileAttributes.Hidden) != FileAttributes.Hidden & fileInfo.Extension != ".gz")
        {
            // Create the compressed file.
            using (FileStream outFile = File.Create(fileInfo.FullName + ".gz"))
            {
                using (GZipStream Compress = new GZipStream(outFile, CompressionMode.Compress))
                {
                    // Copy the source file into 
                    // the compression stream.
                    Timer.Start();
                    inFile.CopyTo(Compress);
                    Timer.Stop();

                    Console.WriteLine("Compressed {0} from {1} to {2} bytes in {3} seconds.",
                        fileInfo.Name, fileInfo.Length.ToString(), outFile.Length.ToString(), ((double)Timer.ElapsedMilliseconds / 1000));
                }
            }
        }
    }
}

谢谢!

【问题讨论】:

  • 文件之间是否有任何已知的重叠,还有什么可以用来进一步逻辑压缩内容的吗?
  • 让 Windows 来做这件事。右键单击文件夹,属性,高级,勾选“压缩内容”选项。
  • @HansPassant 那么编程的潜在性能收益不值得麻烦吗? (另外,我假设有一种方法可以安排窗口来执行此操作?)
  • Windows 可以很多 更有效地执行此操作,它发生在后台内核工作线程上。无需安排,您将其打开,它将始终处于活动状态。文件数据在写入磁盘时会被压缩。并在您阅读时自动解压缩。
  • @HansPassant 很酷,谢谢我不知道

标签: c# .net-4.0 compression console-application


【解决方案1】:

这个答案:Is it safe to call ICsharpCode.SharpZipLib in parallel on multiple threads

提供了一些 GZIP 压缩替代方案的比较。

您的数据足够大,可以从并行压缩中受益。

This sample code 进行并行压缩。

与内置的 GZipStream 相比,并行方法需要大约一半的时间并呈现“稍微好一点”的压缩效果。

DotNetZip 也有用于 BZip2 压缩的类(包括并行实现)。 BZip2 比 GZIP 慢得多,但可以提供更好的压缩比。

【讨论】:

  • 结束了对我的代码进行并行压缩,但可能只是按照 Hans 的建议让 windows 处理它。
【解决方案2】:

没有通用的方法。您需要为

  • 有效载荷
  • 文件系统
  • CPU 负载和容量

你可以通过Level parameter to the GZipStream Constructor

我会考虑使用预先存在的(外部)工具来完成这项工作。使用比较基准会更快,因为您不必去实施它们。我真的建议使用类似 unix 的工具,但您可能很难为您的 Windows 平台找到它们

【讨论】:

  • 关于“您可能找不到...”有一个用于 Windows 的 tar 文件,它在 cheeso.members.winisp.net/srcview.aspx?dir=Tar 处进行 GZIP 压缩。 DotNetZip 中包含一个并行 bzip 库。
  • 请注意,我也链接到了那里的几个工具。
猜你喜欢
  • 2014-11-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2010-11-08
  • 2021-01-13
  • 1970-01-01
相关资源
最近更新 更多