2
votes

I'm using the .Net GZipStream class to compress and decompress files. After I do the decompression, the data seems fine, but then turns to nothing but zeros after a certain, seemingly arbitrary, point. For example, after decompressing a file, it is the proper 19KB in size, but bytes 10,588 and on are all zeros.

I'm not sure what I'm doing incorrectly.

This is how I do the compression:

Byte[] bytes = GetFileBytes(file);

using (FileStream fileStream = new FileStream("Zipped.gz", FileMode.Create))
{
    using (GZipStream zipStream = new GZipStream(fileStream, CompressionMode.Compress))
    {
        zipStream.Write(bytes, 0, bytes.Length);
    }
}

And this is how I do the decompression (Bytes is the array of compressed bytes, and OriginalSize is the size of the file before it was compressed):

using (MemoryStream memoryStream = new MemoryStream(Bytes))
{
    using (GZipStream zipStream = new GZipStream(memoryStream, CompressionMode.Decompress))
    {
        // Note: Since the compressed version can be larger, I use the larger of the original and the compressed size for the decompressed array's size.
        Byte[] decompressedBytes = new Byte[OriginalSize > Bytes.Length ? OriginalSize : Bytes.Length];

        Int32 numRead = zipStream.Read(decompressedBytes, 0, Bytes.Length);

        using (FileStream fileStream = new FileStream("Decompressed.txt", Name), FileMode.Create))
        {
            fileStream.Write(decompressedBytes, 0, Convert.ToInt32(OriginalSize));
        }
    }
}
1
Do you know if it is in the decompression or compression - you could check this by decompressing/compressing the file by hand using gzip.Michael Anderson

1 Answers

3
votes

I see a potential error here: you make assumptions! :) You have to use a loop when copying between the streams, see this question