views:

33

answers:

1

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));
        }
    }
}
+3  A: 

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

Onkelborg
Hm, nope :) Take a look at that link again :) (You could even use the methods there, it's easiest)
Onkelborg