开发者

PHP's 'gzuncompress' function in C#?

开发者 https://www.devze.com 2023-03-27 20:19 出处:网络
PHP\'s \'gzuncompress\'function in C#? Is there a function similar to PHPsgzuncompress in 开发者_运维问答C#? You would use a GZipStream to read over the data. This is especially convenient if the sou

PHP's 'gzuncompress' function in C#? Is there a function similar to PHPs gzuncompress in 开发者_运维问答C#?


You would use a GZipStream to read over the data. This is especially convenient if the source is itself a Stream, but if you have a byte[], just use a new MemoryStream(existingData):

private static byte[] GZipUncompress(byte[] data)
{
    using(var input = new MemoryStream(data))
    using(var gzip = new GZipStream(input, CompressionMode.Decompress))
    using(var output = new MemoryStream())
    {
        gzip.CopyTo(output);
        return output.ToArray();
    }
}

and also:

private static byte[] GZipCompress(byte[] data)
{
    using(var input = new MemoryStream(data))
    using (var output = new MemoryStream())
    {
        using (var gzip = new GZipStream(output, CompressionMode.Compress, true))
        {
            input.CopyTo(gzip); 
        }
        return output.ToArray();
    }
}

Note also that the "inflate"/"deflate" methods will be similar, but using a DeflateStream.

Note that I'm only using byte[] methods here for convenience; you should generally prefer the Stream-based API, since that scales to large data much more conveniently.

0

精彩评论

暂无评论...
验证码 换一张
取 消