我必须压缩responseStream但是流不可写。我已编写此代码但它不起作用(C#中的GZip压缩)

时间:2013-05-29 05:11:39

标签: c# gzip

try
{
   TextReader reader = new StreamReader(responseStream);
   gzipBytes = ASCIIEncoding.ASCII.GetBytes(reader.ToString());

   MemoryStream ms = new MemoryStream();
   // Use the newly created memory stream for the compressed data.
   outStream = new GZipStream(ms, CompressionMode.Compress, true);
   outStream.Write(gzipBytes, 0, gzipBytes.Length);
   // Close the stream.
 }
 catch
 {
 }

1 个答案:

答案 0 :(得分:0)

尝试一下,看看它是否适合你:

using (Stream inputStream = ...)
using (MemoryStream outputStream = new MemoryStream())
using (GZipStream zipStream = new GZipStream(outputStream, CompressionMode.Compress, true))
{
    inputStream.CopyTo(zipStream);
}

您需要做的就是将第一行Stream inputStream = ...替换为输入流,例如:Stream inputStream = File.OpenRead(...)Stream inputStream = new StreamReader(...) ......无论如何。应该复制到zipStream并执行压缩。

此外,using块也不错。他们释放了非托管资源,而不是让它们漂浮,直到垃圾收集器拿起它们。