Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do I need two calls to stream CopyTo?

Tags:

c#

stream

c#-4.0

I have the following method and for some reason the first call to Copy to seems to do nothing? Anyone know why? In input to the method is compressed and base64 can supply that method to if need.

private byte[] GetFileChunk(string base64)
    {
        using (
            MemoryStream compressedData = new MemoryStream(Convert.FromBase64String(base64), false),
            uncompressedData = new MemoryStream())
        {

            using (GZipStream compressionStream = new GZipStream(compressedData, CompressionMode.Decompress))
            {
                // first copy does nothing ?? second works
                compressionStream.CopyTo(uncompressedData);
                compressionStream.CopyTo(uncompressedData);
            }

            return uncompressedData.ToArray();
        }
    }
like image 230
Dan H Avatar asked Aug 09 '10 12:08

Dan H


1 Answers

If the first call to Read() returns 0 then Stream.CopyTo() isn't going to work either. While this points to a problem with GZipStream, it is very unlikely that it has a bug like this. Far more likely is that something went wrong when you created the compressed data. Like compressing 0 bytes first, followed by compressing the real data.

like image 85
Hans Passant Avatar answered Sep 19 '22 13:09

Hans Passant