しばらくの間問題なくGZipStreamを使用していました。私は自分の関数でコードを変更しませんでしたが、今は圧縮と解凍が機能しません。私は次の簡単な例を抽出しました(おそらく私は一般的に何か間違っています...)。C#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"
です... Unzip
で
任意のメモリを複製回避all:https://dotnetfiddle.net/BCSheL。あなたのエラーが正しく再現されるように、そのフィドルを編集してください。 –
これは偶然にしか機能しません。 Encoding.UTF8は任意のバイト値を処理できません。有効なUnicodeコードポイントでなければなりません。バイト[]を符号化するにはConvert.To/FromeBase64String()が必要です。 Unzip()メソッドにms.Position = 0が指定されていません。これはこれまでに働いたことがない、あなたはこれに気付かないことにかなり気をつけなければならない。 –