Reynevan
Reynevan

Reputation: 1545

GZIPStream Compression Always Returns 10 Bytes

I'm trying to compress some text in my UWP application. I created this method to make it easier later on:

public static byte[] Compress(this string s)
{
    var b = Encoding.UTF8.GetBytes(s);
    using (MemoryStream ms = new MemoryStream())
    using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
    {
        zipStream.Write(b, 0, b.Length);
        zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
        return ms.ToArray();
    }
}

But unfortunately this always returns 10 bytes, no matter what the input text is. Is it because I don't use .Close() on the GZipStream?

Upvotes: 4

Views: 1855

Answers (1)

Vincent
Vincent

Reputation: 3746

You are returning the byte data too early. The Close() method is replaced by the Dispose() method. So the GZIP stream will be written only when disposed so after you leave the using(GZipStream) {} block.

public static byte[] Compress(string s)
{
    var b = Encoding.UTF8.GetBytes(s);
    var ms = new MemoryStream();
    using (GZipStream zipStream = new GZipStream(ms, CompressionMode.Compress))
    {
        zipStream.Write(b, 0, b.Length);
        zipStream.Flush(); //Doesn't seem like Close() is available in UWP, so I changed it to Flush(). Is this the problem?
    }

    // we create the data array here once the GZIP stream has been disposed
    var data    = ms.ToArray();
    ms.Dispose();
    return data;
}

Upvotes: 10

Related Questions