Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GZipStream compression not working

Tags:

c#

gzipstream

I'm trying to read in a file and compress it using GZipStream, like this:

using (var outStream = new MemoryStream())
{
    using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
        {
            fileStream.CopyTo(gzipStream);

            Debug.WriteLine(
                "Compressed from {0} to {1} bytes", 
                fileStream.Length, 
                outStream.Length);

            // "outStream" is utilised here (persisted to a NoSql database).
        }
    }
} 

The problem is that outStream.Length always shows 10 bytes. What am I doing wrong?

I've tried calling gzipStream.Close() after the fileStream.CopyTo line (as suggested in other forums) but this seems to close outStream too, so the subsequent code that uses it falls over.

like image 938
Andrew Stephens Avatar asked Dec 06 '13 12:12

Andrew Stephens


1 Answers

MSDN says: The write operation might not occur immediately but is buffered until the buffer size is reached or until the Flush or Close method is called.

In other words, the fact that all the Write operations are done doesn't mean the data is already in the MemoryStream. You have to do gzipStream.Flush() or close the gzipStream first.

Example:

using (var outStream = new MemoryStream())
{
    using (var fileStream = new FileStream(filename, FileMode.Open, FileAccess.Read))
    {
        using (var gzipStream = new GZipStream(outStream, CompressionMode.Compress))
        {
            fileStream.CopyTo(gzipStream);
        }

        Debug.WriteLine(
                "Compressed from {0} to {1} bytes", 
                fileStream.Length, 
                outStream.Length);

        // "outStream" is utilised here (persisted to a NoSql database).
    }
} 

Also, ideally, put it outside of the FileStream as well - you want to close files as soon as you can, rather than waiting for some other processing to finish.

like image 69
Luaan Avatar answered Oct 06 '22 00:10

Luaan