GZipStream只解压缩第一行



我的GZipStream只会解压缩文件的第一行。 通过 7-zip 提取内容按预期工作,并为我提供了整个文件内容。 它还在cygwin和linux上使用gunzip按预期提取,所以我希望这是特定于OS/S的(Windows 7)。

不确定如何对此进行故障排除,因此任何有关此的提示都会对我有很大帮助。 这听起来与此非常相似,但是使用SharpZLib会产生同样的结果。

这是我正在做的事情:

var inputFile = String.Format(@"{0}{1}", inputDir, fileName);
var outputFile = String.Format(@"{0}{1}.gz", inputDir, fileName);
var dcmpFile = String.Format(@"{0}{1}", outputDir, fileName);
    using (var input = File.OpenRead(inputFile)) 
    using (var fileOutput = File.Open(outputFile, FileMode.Append))
    using (GZipStream gzOutput = new GZipStream(fileOutput, CompressionMode.Compress, true))
    {
        input.CopyTo(gzOutput);
    }
// Now, decompress
using (FileStream of = new FileStream(outputFile, FileMode.Open, FileAccess.Read))
using (GZipStream ogz = new GZipStream(of, CompressionMode.Decompress, false))
using (FileStream wf = new FileStream(dcmpFile, FileMode.Append, FileAccess.Write))
{
    ogz.CopyTo(wf); 
}

您的输出文件仅包含一行(gzipped) - 但它包含除换行符以外的所有文本数据。

您反复调用 ReadLine() 它会返回一行不带换行符的文本并将该文本转换为字节。因此,如果您有一个具有以下功能的输入文件:

abc
def
ghi

你最终会得到一个输出文件,它是压缩版本的

abcdefghi

如果你不想要这种行为,为什么还要首先经历StreamReader?只需一次从输入FileStream直接复制到GZipStream块,或者如果您使用的是 .NET 4,请使用Stream.CopyTo

// Note how much simpler the code is using File.*
using (var input = File.OpenRead(inputFile))
using (var fileOutput = File.Open(outputFile, FileMode.Append))
using (GZipStream gzOutput = new GZipStream(os, CompressionMode.Compress, true)) 
{
    input.CopyTo(gzOutput);
}

另请注意,附加到压缩文件很少是一个好主意,除非您对单个文件中的多个"块"进行了某种特殊处理。

最新更新