在GZipStream中设置缓冲区大小

时间:2013-09-01 04:42:35

标签: c# http proxy stream gzip

我在c#中写了一个轻量级的代理。当我解码gzip contentEncoding时,我注意到如果我使用一个小的缓冲区大小(4096),则根据输入的大小对流进行部分解码。它是我的代码中的错误还是需要使其工作的东西?我将缓冲区设置为10 MB,它可以正常运行,但是无法实现我编写轻量级代理的目的。

 response = webEx.Response as HttpWebResponse;
 Stream input = response.GetResponseStream();
 //some other operations on response header

 //calling DecompressGzip here


private static string DecompressGzip(Stream input, Encoding e)
    {


        StringBuilder sb = new StringBuilder();

        using (Ionic.Zlib.GZipStream decompressor = new Ionic.Zlib.GZipStream(input, Ionic.Zlib.CompressionMode.Decompress))
        {
           // works okay for [1024*1024*8];
            byte[] buffer = new byte[4096];
            int n = 0;

                do
                {
                    n = decompressor.Read(buffer, 0, buffer.Length);
                    if (n > 0)
                    {
                        sb.Append(e.GetString(buffer));
                    }

                } while (n > 0);

        }

        return sb.ToString();
    }

1 个答案:

答案 0 :(得分:0)

实际上,我想通了。我想使用字符串生成器会导致问题;相反,我使用了一个内存流,效果很好。

private static string DecompressGzip(Stream input, Encoding e)
    {

        using (Ionic.Zlib.GZipStream decompressor = new Ionic.Zlib.GZipStream(input, Ionic.Zlib.CompressionMode.Decompress))
        {

            int read = 0;
            var buffer = new byte[4096];

            using (MemoryStream output = new MemoryStream())
            {
                while ((read = decompressor.Read(buffer, 0, buffer.Length)) > 0)
                {
                    output.Write(buffer, 0, read);
                }
                return e.GetString(output.ToArray());
            }


        }

    }