【发布时间】:2017-05-09 12:47:25
【问题描述】:
我使用 GZipStream 有一段时间了,没有任何问题。我没有在我的函数中更改任何代码,但现在压缩和解压缩不起作用。我提取了以下简单的示例(也许我通常做错了什么......)。
public static class ZipLib
{
#region Public Methods
public static string Unzip(byte[] compressedText)
{
try {
byte[] gzBuffer = compressedText;
int msgLength = BitConverter.ToInt32(gzBuffer, 0);
byte[] buffer = new byte[msgLength];
using (MemoryStream ms = new MemoryStream()) {
ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress, true)) {
zip.Read(buffer, 0, buffer.Length);
}
}
return Encoding.UTF8.GetString(buffer);
}
catch (Exception ex) {
Debug.WriteLine(ex.Message);
}
return "";
}
public static byte[] Zip(string text)
{
byte[] buffer = Encoding.UTF8.GetBytes(text);
MemoryStream ms = new MemoryStream();
using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true)) {
zip.Write(buffer, 0, buffer.Length);
}
ms.Position = 0;
byte[] compressed = new byte[ms.Length];
ms.Read(compressed, 0, compressed.Length);
byte[] gzBuffer = new byte[compressed.Length + 4];
Buffer.BlockCopy(compressed, 0, gzBuffer, 4, compressed.Length);
Buffer.BlockCopy(BitConverter.GetBytes(buffer.Length), 0, gzBuffer, 0, 4);
return gzBuffer;
}
#endregion
}
internal class Program
{
#region Private Methods
private static void Main(string[] args)
{
string uncompressedIn = "Hallo Welt";
var compressed = ZipLib.Zip(uncompressedIn);
var uncompressed = ZipLib.Unzip(compressed);
Console.WriteLine("Uncompressed Input: " + uncompressedIn);
Console.WriteLine("Compressed value: " + string.Join(" | ", compressed));
Console.WriteLine("Uncompressed from compressed: " + string.Join(" | ", uncompressed.ToCharArray()));
Console.ReadKey();
}
#endregion
}
uncompressed 的值为"\0\0\0\0"...
【问题讨论】:
-
我尝试使用提供的代码重新创建您的问题,但我根本没有得到任何输出:dotnetfiddle.net/BCSheL。只需编辑该小提琴,以便正确重新创建错误。
-
这只能是偶然的。 Encoding.UTF8 不能处理任意字节值,它们必须是有效的 Unicode 代码点。对 byte[] 进行编码需要 Convert.To/FromeBase64String()。 Unzip() 方法缺少 ms.Position = 0;这以前从未奏效过,您应该非常担心没有早点注意到这一点。