LoginSignup
2
2

More than 5 years have passed since last update.

PHPでgzcompressされたデータをC#で展開する

Last updated at Posted at 2014-02-04

Problem

PHPのgzcompressはgzipではなくzlibなので,.NET FrameworkのGZipStreamさんが対応に困ります。曰くマジックナンバーがないとのこと。

Solution

なければ足せばいいではないかということです。

decompress.cs
byte[] gzdata = Convert.FromBase64String(request.Data);
using (var ms = new MemoryStream())
{
    if ((gzdata[0] != 0x1f) && (gzdata[1] != 0x8b))
    {
        ms.Write(new byte[] {0x1f, 0x8b, 0x08, 0x00,
                                0x00, 0x00, 0x00, 0x00}, 0, 8);
    }
    ms.Write(gzdata, 0, gzdata.Length);
    ms.Position = 0;
    using (var gz = new GZipStream(ms, CompressionMode.Decompress))
    using (var reader = new StreamReader(gz))
    {
        return reader.ReadToEnd();
    }
}

追記:この方法はMono環境では正常に動作しません。Zlib.netなど別の方法を取る必要があります。

See also...

下記を参考にしました。関連情報からいろいろ情報が。
http://stackoverflow.com/questions/4080344/decompress-string-in-c-sharp-which-were-compressed-by-phps-gzcompress

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2