GZipStream压缩不起作用

时间:2013-12-06 12:06:40

标签: c# gzipstream

我正在尝试读取文件并使用GZipStream对其进行压缩,如下所示:

using (var outStream = new MemoryStream())
{
    using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
        {
            fileStream.CopyTo(gzipStream);

            Debug.WriteLine(
                "Compressed from {0} to {1} bytes", 
                fileStream.Length, 
                outStream.Length);

            // "outStream" is utilised here (persisted to a NoSql database).
        }
    }
} 

问题是outStream.Length总是显示10个字节。我做错了什么?

我尝试在gzipStream.Close()行之后调用fileStream.CopyTo(正如其他论坛中所建议的那样),但这似乎也关闭outStream,因此后续使用它的代码会失败。

1 个答案:

答案 0 :(得分:5)

MSDN说:The write operation might not occur immediately but is buffered until the buffer size is reached or until the Flush or Close method is called.

换句话说,完成所有写操作的事实并不意味着数据已经在MemoryStream中。您必须先执行gzipStream.Flush()或关闭gzipStream。

示例:

using (var outStream = new MemoryStream())
{
    using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
        {
            fileStream.CopyTo(gzipStream);
        }

        Debug.WriteLine(
                "Compressed from {0} to {1} bytes", 
                fileStream.Length, 
                outStream.Length);

        // "outStream" is utilised here (persisted to a NoSql database).
    }
} 

另外,理想情况下,也将它放在FileStream之外 - 您希望尽快关闭文件,而不是等待其他一些处理完成。