.net framework 4.0 c# 中的文件压缩
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 
原文地址: http://stackoverflow.com/questions/17086374/
Warning: these are provided under cc-by-sa 4.0 license.  You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
File compression in .net framework 4.0 c#
提问by user2385057
Are there any built-in classes/examples for version 4.0 to compress specific files from a directory? I found an example on MSDN which uses the compression class but it is only for version 4.5 & above.
4.0 版是否有任何内置类/示例来压缩目录中的特定文件?我在 MSDN 上找到了一个使用压缩类的示例,但它仅适用于 4.5 及更高版本。
回答by Soner G?nül
You can use GZipStreamand DeflateStreamclasses which includes also .NET Framework 4.
您可以使用GZipStream和DeflateStream类还包括.NET Framework 4中。
Check How to: Compress Filesfrom MSDN.
How to: Compress Files从 MSDN检查。
Use the System.IO.Compression.GZipStream class to compress and decompress data. You can also use the System.IO.Compression.DeflateStream class, which uses the same compression algorithm; however, compressed GZipStream objects written to a file that has an extension of .gz can be decompressed using many common compression tools.
使用 System.IO.Compression.GZipStream 类来压缩和解压缩数据。您还可以使用 System.IO.Compression.DeflateStream 类,它使用相同的压缩算法;但是,写入扩展名为 .gz 的文件的压缩 GZipStream 对象可以使用许多常见的压缩工具进行解压缩。
An example from here:
这里的一个例子:
Compressing a file using GZipStream
使用 GZipStream 压缩文件
FileStream sourceFileStream = File.OpenRead("sitemap.xml");
FileStream destFileStream = File.Create("sitemap.xml.gz");
GZipStream compressingStream = new GZipStream(destFileStream,
    CompressionMode.Compress);
byte[] bytes = new byte[2048];
int bytesRead;
while ((bytesRead = sourceFileStream.Read(bytes, 0, bytes.Length)) != 0)
{
    compressingStream.Write(bytes, 0, bytesRead);
}
sourceFileStream.Close();
compressingStream.Close();
destFileStream.Close();
Decompressing a file using GZipStream
使用 GZipStream 解压缩文件
FileStream sourceFileStream = File.OpenRead("sitemap.xml.gz");
FileStream destFileStream = File.Create("sitemap.xml");
GZipStream decompressingStream = new GZipStream(sourceFileStream,
    CompressionMode.Decompress);
int byteRead;
while((byteRead = decompressingStream.ReadByte()) != -1)
{
    destFileStream.WriteByte((byte)byteRead);
}
decompressingStream.Close();
sourceFileStream.Close();
destFileStream.Close();
回答by 0b101010
I've done a lot of file compression work over the years and by far the best option I found is to use DotNetZip
多年来我做了很多文件压缩工作,到目前为止我发现的最佳选择是使用 DotNetZip
Better than GZipStreamand the other BCL offerings. It has a friendly API and provides significant functionality.
比GZipStream其他 BCL 产品更好。它具有友好的 API 并提供重要的功能。

