Search code examples
c#gzipmemorystreamgzipstream

Compression stream appears empty


I need to compress a file using GZip by batch of specified size (not in a whole). I can successfuly fill the byte[] buffer, but after copying it into the compression stream, it just leaves the output stream empty.

public void Compress(string source, string output)
    {
        FileInfo fi = new FileInfo(source);
        byte[] buffer = new byte[BufferSize];
        int total, current = 0;
        using (FileStream inFile = fi.OpenRead())
        {
            using (FileStream outFile = File.Create(output + ".gz"))
            {
                while ((total = inFile.Read(buffer, 0, buffer.Length)) != 0)
                {
                    using (MemoryStream compressedStream = new MemoryStream())
                    {
                        using (MemoryStream bufferStream = new MemoryStream())
                        {
                            CopyToStream(buffer, bufferStream);
                            using (GZipStream Compress = new GZipStream(compressedStream, CompressionMode.Compress, true))
                            {
                                bufferStream.Position = 0;
                                bufferStream.CopyTo(Compress);
                                current += total;
                            }
                            compressedStream.Position = 0;
                            compressedStream.CopyTo(outFile);
                        }
                    }
                }
            }
        }
    }

    static void CopyToStream(byte[] buffer, Stream output)
    {
        output.Write(buffer, 0, buffer.Length);
    }

Solution

  • You need to rewind compressedStream by setting Position=0 before compressedStream.CopyTo(outFile);.