如何将 GZipStream 与 System.IO.MemoryStream 一起使用? [英] How do I use GZipStream with System.IO.MemoryStream?
问题描述
我遇到了这个测试函数的问题,我在内存中取出一个字符串,压缩它,然后解压它.压缩效果很好,但我似乎无法让解压工作.
I am having an issue with this test function where I take an in memory string, compress it, and decompress it. The compression works great, but I can't seem to get the decompression to work.
//Compress
System.IO.MemoryStream outStream = new System.IO.MemoryStream();
GZipStream tinyStream = new GZipStream(outStream, CompressionMode.Compress);
mStream.Position = 0;
mStream.CopyTo(tinyStream);
//Decompress
outStream.Position = 0;
GZipStream bigStream = new GZipStream(outStream, CompressionMode.Decompress);
System.IO.MemoryStream bigStreamOut = new System.IO.MemoryStream();
bigStream.CopyTo(bigStreamOut);
//Results:
//bigStreamOut.Length == 0
//outStream.Position == the end of the stream.
我相信 bigStream out 中至少应该有数据,尤其是当我的源流 (outStream) 正在被读取时.这是 MSFT 的错误还是我的错误?
I believe that bigStream out should at least have data in it, especially if my source stream (outStream) is being read. is this a MSFT bug or mine?
推荐答案
在您的代码中发生的情况是您不断打开流,但从未关闭它们.
What happens in your code is that you keep opening streams, but you never close them.
在第 2 行中,您创建了一个
GZipStream
.这个流不会向底层流写入任何内容,直到它感觉到了合适的时间.您可以通过关闭它来告诉它.
In line 2, you create a
GZipStream
. This stream will not write anything to the underlying stream until it feels it’s the right time. You can tell it to by closing it.
但是,如果您关闭它,它也会关闭底层流 (outStream
).因此,您不能在其上使用 mStream.Position = 0
.
However, if you close it, it will close the underlying stream (outStream
) too. Therefore you can’t use mStream.Position = 0
on it.
您应该始终使用 using
来确保关闭所有流.这是您的代码的一个变体.
You should always use using
to ensure that all your streams get closed. Here is a variation on your code that works.
var inputString = "" ... "";
byte[] compressed;
string output;
using (var outStream = new MemoryStream())
{
using (var tinyStream = new GZipStream(outStream, CompressionMode.Compress))
using (var mStream = new MemoryStream(Encoding.UTF8.GetBytes(inputString)))
mStream.CopyTo(tinyStream);
compressed = outStream.ToArray();
}
// "compressed" now contains the compressed string.
// Also, all the streams are closed and the above is a self-contained operation.
using (var inStream = new MemoryStream(compressed))
using (var bigStream = new GZipStream(inStream, CompressionMode.Decompress))
using (var bigStreamOut = new MemoryStream())
{
bigStream.CopyTo(bigStreamOut);
output = Encoding.UTF8.GetString(bigStreamOut.ToArray());
}
// "output" now contains the uncompressed string.
Console.WriteLine(output);
这篇关于如何将 GZipStream 与 System.IO.MemoryStream 一起使用?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!