GZip解压缩提供空白文件

本文关键字:空白 文件 解压缩 GZip | 更新日期: 2023-09-27 17:59:14

给定下面的代码,为什么解压缩不起作用?"NewFile2.txt"应该有原始的解压文本,但文件只是空白的。

ioTests.CompressFile(@"c:'newfile.txt", @"c:'newfile.txt.gz");
ioTests.DecompressFile(@"c:'newfile.txt.gz", @"c:'newfile2.txt");
public void CompressFile(string inFileName, string outFileName)
{
    FileStream inFile = new FileStream(inFileName, FileMode.Open);
    FileStream outFile = new FileStream(outFileName, FileMode.Create);
    GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
    int theByte = inFile.ReadByte();
    while (theByte != -1)
    {
        compStream.WriteByte((byte)theByte);
        theByte = inFile.ReadByte();
    }
    compStream.Close();
}
public void DecompressFile(string inFileName, string outFileName)
{
    FileStream inFile = new FileStream(inFileName, FileMode.Open);
    FileStream outFile = new FileStream(outFileName, FileMode.CreateNew);
    GZipStream compStream = new GZipStream(inFile, CompressionMode.Decompress);
    int theByte = compStream.ReadByte();
    while (theByte != -1)
    {
        outFile.WriteByte((byte)theByte);
        theByte = compStream.ReadByte();
    }
    compStream.Close();
}

GZip解压缩提供空白文件

outFile.Flush(); // after your loop

我更喜欢

outFile.Close() 

因为这会刷新流并调用Dispose方法,从而释放分配的资源。

由于您使用的流实现了IDisposable接口,因此您应该Dispose()/Close()您的类,或者使用using语句自动执行此操作:

    using (FileStream inFile = new FileStream(inFileName, FileMode.Open))
    using (FileStream outFile = new FileStream(outFileName, FileMode.Create))
    using (GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress)) {
        int theByte = inFile.ReadByte();
        // ... Rest of your code
    }

大致翻译为:

    try {
       FileStream inFile = new FileStream(inFileName, FileMode.Open);
       FileStream outFile = new FileStream(outFileName, FileMode.Create);
       GZipStream compStream = new GZipStream(outFile, CompressionMode.Compress);
        int theByte = inFile.ReadByte();
        // ... Rest of your code
    } finally {
        if (inFile != null) inFile.Dispose();
        if (outFile != null) outFile.Dispose();
        if (compStream != null) compStream.Dispose();
    }