如何在C#中解压缩GZip压缩字符串



我目前正在尝试解压缩GZip压缩字符串,我正在使用以下函数:

private static string Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
using (var memoryStreamOutput = new MemoryStream()) 
{
gZipStream.CopyTo(memoryStreamOutput);
var outputBytes = memoryStreamOutput.ToArray();
string decompressed = Encoding.UTF8.GetString(outputBytes);
return decompressed;
}
}

每当我运行代码时,我在调用函数时插入的字符串在应该解压缩的地方是不变的。我也尝试过使用StreamReader,但都不起作用。发生了什么?

如果我们首先对它的压缩方式做出合理的假设,那么显示的代码运行得很好:

using System;
using System.IO;
using System.IO.Compression;
using System.Text;
static class P
{
static void Main()
{
Console.WriteLine(lipsum.Length); // 61125 chars of lipsum (not shown)
Console.WriteLine(Encoding.UTF8.GetByteCount(lipsum)); // 61125 bytes of lipsum
var bytes = Compress(lipsum);
Console.WriteLine(bytes.Length); // 16795 bytes compressed
var value = Decompress(bytes);
Console.WriteLine(value.Length); // 61125 bytes again when decompressed
Console.WriteLine(value == lipsum); // True - it worked fine
}
private static byte[] Compress(string value)
{
using (var memoryStream = new MemoryStream())
{
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Compress))
{
gZipStream.Write(Encoding.UTF8.GetBytes(value));
}
return memoryStream.ToArray();
}
}
private static string Decompress(byte[] bytes)
{
using (var memoryStream = new MemoryStream(bytes))
using (var gZipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
using (var memoryStreamOutput = new MemoryStream())
{
gZipStream.CopyTo(memoryStreamOutput);
var outputBytes = memoryStreamOutput.ToArray();
string decompressed = Encoding.UTF8.GetString(outputBytes);
return decompressed;
}
}
// MASSIVELY TRUNCATED FOR POST!
const string lipsum = @"Lorem ipsum dolor sit amet,  ... ac dolor ac hendrerit.";
}

相关内容

  • 没有找到相关文章

最新更新