C#解压缩.GZip到文件

时间:2014-09-20 20:28:33

标签: c#

我有这个代码

using System.IO;
using System.IO.Compression;
...
UnGzip2File("input.gz","output.xls");

运行此过程,它运行时没有错误但在此之后,input.gz为空并且创建的output.xls也为空。在开始时input.gz有12MB​​。我究竟做错了什么 ?或者你有更好/功能解决方案吗?

public static void UnGzip2File(string inputPath, string outputPath) 
        {
            FileStream inputFileStream = new FileStream(inputPath, FileMode.Create);
            FileStream outputFileStream = new FileStream(outputPath, FileMode.Create);

            using (GZipStream gzipStream = new GZipStream(inputFileStream, CompressionMode.Decompress))
            {
                byte[] bytes = new byte[4096];
                int n;

                // To be sure the whole file is correctly read, 
                // you should call FileStream.Read method in a loop, 
                // even if in the most cases the whole file is read in a single call of FileStream.Read method.

                while ((n = gzipStream.Read(bytes, 0, bytes.Length)) != 0)
                {
                    outputFileStream.Write(bytes, 0, n);
                }
            }

            outputFileStream.Dispose();
            inputFileStream.Dispose();
        }

1 个答案:

答案 0 :(得分:1)

使用FileStream打开FileMode.Create将覆盖文档here中的现有文件。当您尝试解压缩文件时,这将导致文件为空,这反过来会导致输出文件为空。

下面是一个工作代码示例,请注意它是异步的,可以通过省略async / await并将调用更改为常规CopyTo方法并将返回类型更改为void来更改。

public static async Task DecompressGZip(string inputPath, string outputPath)
{
    using (var input = File.OpenRead(inputPath))
    using (var output = File.OpenWrite(outputPath))
    using (var gz = new GZipStream(input, CompressionMode.Decompress))
    {
        await gz.CopyToAsync(output);
    }
}