【问题标题】:Setting Buffer Size in GZipStream在 GZipStream 中设置缓冲区大小
【发布时间】:2013-09-01 04:42:35
【问题描述】:

我正在用 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();
    }

【问题讨论】:

    标签: c# http proxy stream gzip


    【解决方案1】:

    实际上,我想通了。我猜使用字符串生成器会导致问题;相反,我使用了内存流,它运行良好。

    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());
                }
    
    
            }
    
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-07-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-10
      • 2015-05-18
      • 2017-05-29
      相关资源
      最近更新 更多