duangu6431 2010-11-02 17:23
浏览 241

在c#中解压缩由php的gzcompress()压缩的字符串

i'm querying a webservice in c# 4.0, which provides me with a string compressed by php's gzcompress(). Now i need to decompress this string in c#. I tried several ways including

but everytime i get an "Missing Magic Number" exception.

Can someone provide me with some hints?

Thank you

Edit 1:

My latest try:

public static string Decompress(string compressed) {
    byte[] compressedBytes = Encoding.ASCII.GetBytes(compressed);
    MemoryStream mem = new MemoryStream(compressedBytes);
    GZipStream gzip = new GZipStream(mem, CompressionMode.Decompress);
    StreamReader reader = new StreamReader(gzip);
    return reader.ReadToEnd();
}
  • 写回答

1条回答 默认 最新

  • duanpao4522 2010-11-02 18:35
    关注

    Well, there you go, with a little help from @boas.anthro.mnsu.edu:

    using (var mem = new MemoryStream())
    {
        mem.Write(new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
        mem.Write(inputBytes, 0, inputBytes.Length);
    
        mem.Position = 0;
    
        using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
        using (var reader = new StreamReader(gzip))
        {
            Console.WriteLine(reader.ReadToEnd());
        }
    }
    

    The trick is to add a magic header. Note that this does not work with SharpZipLib. It complains that there is not footer. However, the .NET decompresser works perfectly.

    One more thing. The comment concerning the ASCII.GetBytes() is correct: your input isn't ASCII. I achieved this result with the following:

    // From PHP:
    
    <?php echo base64_encode(gzcompress("Hello world!")); ?>
    
    // In C#:
    
    string input = "eJzzSM3JyVcozy/KSVEEAB0JBF4=";
    
    byte[] inputBytes = Convert.FromBase64String(input);
    

    With the extra base64 encoding and decoding, this works perfectly.

    If you can't use base64 encoding, you need the raw stream from the PHP page. You can get this using the GetResponseStream():

     var request = WebRequest.Create("http://localhost/page.php");
    
     using (var response = request.GetResponse())
     using (var mem = response.GetResponseStream())
     {
         // Decompression code from above.
     }
    
    评论

报告相同问题?

悬赏问题

  • ¥15 用visual studi code完成html页面
  • ¥15 聚类分析或者python进行数据分析
  • ¥15 逻辑谓词和消解原理的运用
  • ¥15 三菱伺服电机按启动按钮有使能但不动作
  • ¥15 js,页面2返回页面1时定位进入的设备
  • ¥50 导入文件到网吧的电脑并且在重启之后不会被恢复
  • ¥15 (希望可以解决问题)ma和mb文件无法正常打开,打开后是空白,但是有正常内存占用,但可以在打开Maya应用程序后打开场景ma和mb格式。
  • ¥20 ML307A在使用AT命令连接EMQX平台的MQTT时被拒绝
  • ¥20 腾讯企业邮箱邮件可以恢复么
  • ¥15 有人知道怎么将自己的迁移策略布到edgecloudsim上使用吗?