如何在解压缩到C#.NET 2.0中的二进制数据文件后从GZipStream写入二进制数据

时间:2015-01-29 10:20:18

标签: c# gzipstream

如何在C#.NET 2.0中作为二进制数据解压缩到文件后从GZipStream写入二进制数据:

FileStream fileStream = new FileStream("compressed_file.zip", FileMode.Open, FileAccess.Read);
GZipStream compressionStream = new GZipStream(fileStream, CompressionMode.Decompress);

//Now how to save uncompressed binary data in "compressionStream" as a file ???

1 个答案:

答案 0 :(得分:2)

它是一个双线解决方案,您只需要将压缩流复制到文件流。

using (FileStream outFile = new FileStream(sOutFilePath, FileMode.Create, FileAccess.Write, FileShare.None))
                  CopyStream(compressionStream, outFile);

好的,你需要确保你在compressStream的开头,所以添加

compressionStream.Seek(0, SeekOrigin.Begin);

可能是必要的。

编辑:

很抱歉所以copyTo的实现应该是这样的:

public void CopyStream(Stream source, Stream destination, int bufferSize = 81920)
{
    byte[] buffer = new byte[bufferSize];
    int read;
    while ((read = source.Read(buffer, 0, buffer.Length)) != 0)
        destination.Write(buffer, 0, read);
}

EDIT2:

.Net4.5实现中的默认bufferSize定义如下:

private const int _DefaultCopyBufferSize = 81920;

referencesource.microsoft.com

的完整来源