【问题标题】:convert binary data to gzip file and decompress to a string c#将二进制数据转换为 gzip 文件并解压缩为字符串 c#
【发布时间】:2021-05-11 20:36:34
【问题描述】:

我正在尝试解码表示 gzip 文件的二进制数据,我需要解压缩 gzip,以便我可以获取 gzip 中的 nbt(我的世界符号)字符串,但我在 GZipStream 上不断收到以下错误。阅读:

存档条目是使用不受支持的压缩方法压缩的。

有人知道怎么做吗?

这是我的代码:

public static string Decompress(string input)
{
    byte[] compressed = Convert.FromBase64String(input); //This is the binary data
    byte[] decompressed = Decompress(compressed);
    return Encoding.UTF8.GetString(decompressed);
}

private static byte[] Decompress(byte[] input)
{
    using (var source = new MemoryStream(input))
    {
        byte[] lengthBytes = new byte[4];
        source.Read(lengthBytes, 0, 4);

        var length = BitConverter.ToInt32(lengthBytes, 0);
        using (var decompressionStream = new GZipStream(source,
            CompressionMode.Decompress))
        {
            var result = new byte[length];
            decompressionStream.Read(result, 0, length); //Error
            return result;
        }
    }
}

【问题讨论】:

    标签: c# decode


    【解决方案1】:

    这应该为你做:

    public static string Decompress(string value)
    {
        byte[] buffer = Convert.FromBase64String(value);
        byte[] decompressed;
    
        using (var inputStream = new MemoryStream(buffer))
        {
            using var outputStream = new MemoryStream();
    
            using (var gzip = new GZipStream(inputStream, CompressionMode.Decompress, leaveOpen: true))
            {
                gzip.CopyTo(outputStream);
            }
    
            decompressed = outputStream.ToArray();
        }
    
        return Encoding.UTF8.GetString(decompressed);
    }
    

    【讨论】:

    • 谢谢!我明天研究一下。我现在要睡觉了 D;
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-06
    • 1970-01-01
    相关资源
    最近更新 更多