压缩流 [英] Compression Streams

查看:54
本文介绍了压缩流的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试在其中一个程序中实现压缩方法.我希望它接受一个流,对其进行压缩,然后返回压缩后的流(它返回一个流,因为我希望能够将该流传递给另一个函数,而不必将其保存到文件中并在以后重新读取).我有一个基于msdn示例的工作测试版本,该示例基于

I've been trying to implement a compression method in one of my programs. I want it to take in a stream, compress it, and return the compressed stream (It returns a stream because I want to be able to pass the stream to another function without having to save it to a file and re-read it later). I had a working test version based on the msdn example for GZipStream, and this is what I came up with when I tried to convert it to taking in and returning streams:

public static Stream compress(Stream fileToCompress)
{
    using (MemoryStream compressedFileStream = new MemoryStream())
    {
        using (GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress))
        {
            fileToCompress.CopyTo(compressionStream);
            return compressionStream;
        }
    }
}

使用另一种方法将返回的流保存到文件中会导致创建一个0字节的文件(压缩效率很高,是吧?).

Saving the returned stream to a file (in another method) results in a file of 0 bytes being created (pretty efficient compression, huh?).

我尝试寻找其他解决方案,但我无法找到任何使用流的东西,而我进行转换的尝试也遇到了同样的问题.

I've tried looking for other solutions, but I haven't been able to find any that use streams, and my attempts to convert run into the same problem.

仅作记录,我曾尝试使用DeflateStream获得相同的结果.

Just for the record, I have tried using DeflateStream to the same results.

原来是测试程序没有正确保存.感谢您的帮助.

Turns out it was the test program not saving properly. Thanks for the help.

推荐答案

如果您的目标是返回流,则需要将其放入 using 块中

If your goal is to return the stream, you need to not put it in the using block.

类似这样的东西:

public static Stream compress(Stream fileToCompress) {
    MemoryStream compressedFileStream = new MemoryStream();
    GZipStream compressionStream = new GZipStream(compressedFileStream, CompressionMode.Compress);
    fileToCompress.CopyTo(compressionStream);
    compressionStream.Seek(0, SeekOrigin.Begin); // Reset to stream start.
    return compressionStream;
}

否则,当流离开 using 块时,它将在流上调用 Dispose().

Otherwise, when the stream leaves the using block, it calls Dispose() on the stream.

另外,在复制之后,流指针"位于末尾.您需要将指针重新设置为起点.保存之前-显示在这里.

Also, after a copy, the stream "pointer" is at the end. You need to set the pointer back to the start. Before you save - shown here.

删除了所有使用的块.如果需要释放流,则可以手动进行.

Removed all using blocks. If you need to release a stream, you can do it manually.

这篇关于压缩流的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆