【发布时间】:2017-08-18 20:48:22
【问题描述】:
我正在使用下面的方法通过压缩数据来创建一个 Gzip 文件。
public static void GZipCompress(Stream dataToCompress, Stream outputStream)
{
GZipStream gzipStream = new GZipStream(outputStream, CompressionMode.Compress);
int readBufferSize = 10000;
byte[] data_ = new byte[readBufferSize];
int bytesRead = dataToCompress.Read(data_, 0, readBufferSize);
while (bytesRead > 0)
{
gzipStream.Write(data_, 0, bytesRead);
data_ = new byte[readBufferSize];
bytesRead = dataToCompress.Read(data_, 0, readBufferSize);
}
try
{
gzipStream.Flush();
gzipStream.Close();
}
catch (ObjectDisposedException ioException)
{
}
}
但如果它已经是 zip 格式,我不应该压缩它。只需将数据附加到输出 GZip 文件而不进行压缩。我正在使用以下方法。
public static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[16 * 1024]; // Fairly arbitrary size
int bytesRead;
while ((bytesRead = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, bytesRead);
}
output.Flush();
output.Close();
}
当文件的扩展名不包含“zip”时,我将调用 GZipCompress 方法。当文件的扩展名为“zip”时,我正在调用 CopyStream 方法。但是在通过 CopyStream 将内容复制到输出流到 GZip 文件中后,当我尝试解压缩此文件时,出现以下异常。
An unhandled exception of type 'System.IO.InvalidDataException' occurred in System.dll
The magic number in GZip header is not correct. Make sure you are passing in a GZip stream.
是否可以将未压缩的数据写入 GZip 文件?如果是这样,我在这里做错了什么?如果没有,还有其他方法可以实现吗?任何帮助将不胜感激。
【问题讨论】:
-
您可能正在使用 Stream 类的 Write 方法。确保将两个 GZipStream 传递给 CopyStream 方法,或者更好地将参数类型更改为 GZipStream 并执行此操作。
-
即使我通过了GZipStreams,我仍然无法调用GzipStream的write方法。因为那会压缩数据吗?我不希望再次压缩已经压缩的数据:(
-
不是文档。使用 GZipStreams 写入方法写入已压缩的数据。不确定这是否是您需要的。
-
请进一步阅读,我上面的评论似乎是错误的,数据似乎确实被该方法压缩了。对不起。
标签: c# .net-3.5 gzip outputstream gzipstream