GZipStream with large files does not work well

advertisements

I want to compress some very large GML files (1-10GB). I wrote a method for this, but it does not work well. If I decompress it using 7-zip for Windows (or something else), I get the file that looks bad in the end (it's not finished, XML is just not finished)... I don't see what I'm doing wrong...

private void CompressFile()
{
    string outputPath = Path.Combine(Path.ChangeExtension(_gmlPath, ".gz"));

    var buffer = new byte[1024 * 64];
    using (var compressing = new GZipStream(File.OpenWrite(outputPath), CompressionMode.Compress))
    {
        using (var file = File.OpenRead(_gmlPath))
        {
            var bytesRead = file.Read(buffer, 0, buffer.Length);
            while (bytesRead != 0)
            {
                compressing.Write(buffer, 0, buffer.Length);
                bytesRead = file.Read(buffer, 0, buffer.Length);
            }
        }
    }
}

[edit]

Additional question: How can I specify/change the name of file, that is compressed inside GZ? It's name is the same as the input's one, but there is no .gml extention:S (there is in input)...


var bytesRead = file.Read(buffer, 0, buffer.Length);

reads between 1 and 65536 bytes, but

compressing.Write(buffer, 0, buffer.Length);

always writes 65536 bytes, so you're ending up with junk in the file if you read less than 65536 bytes.

Solution: Write only bytesRead many bytes.

compressing.Write(buffer, 0, bytesRead);