【问题标题】:C# GZipStream suddenly not workingC# GZipStream 突然无法正常工作
【发布时间】: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;这以前从未奏效过,您应该非常担心没有早点注意到这一点。

标签: c# string gzip


【解决方案1】:

在Unzip 中,您将Write 转换为MemoryStream,然后将其交给GZipStream 进行读取,但是:它仍在流的末尾,您没有倒带。尝试添加:

ms.Position = 0;

在Write 之后。但是请注意,这样做可能更有效:

using(MemoryStream ms = new MemoryStream(gzBuffer, 4, gzBuffer.Length - 4))
{
     //...
}

这样可以避免复制任何内存

【讨论】:

  • 谢谢,现在可以了。可能是过去的一些代码清理操作导致了这个问题,我太盲目了。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-04-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-02-23
相关资源
最近更新 更多