1

Have been currently trying to decompress a GZip-compressed string where I am using this function:

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;
    }
}

And whenever I run the code, the string I plugged in when calling the function is unchanged where it is supposed to be decompressed. I have also tried using StreamReader, which didn't work neither. What happened?

Wai Ha Lee
  • 8,598
  • 83
  • 57
  • 92
  • 4
    Can you [edit] your question to include some sample input and output which reproduces your issue? – canton7 Mar 23 '20 at 10:47
  • 1
    You mention a "compressed **string**", but your code uses a byte-array. If you received a string, how did you create those bytes? UTF8.GetBytes, Convert.FromBase64String, other? – Hans Kesting Mar 23 '20 at 12:12

1 Answers1

4

The code shown works just fine, if we make reasonable assumptions about how it was compressed in the first place:

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.";
}
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900