Search code examples
c#streammemorystreamgzipstream

How can i read the data using the GZipStream.Read method


I can't read the data using the GZipStream.Read method. But I can read directly from MemoryStream. What am I doing wrong?

    public static void Main(string[] args)
    {
        var memStr = new MemoryStream();

        //Write
        var data = new byte[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
        var gzipWr = new GZipStream(memStr, CompressionMode.Compress);
        gzipWr.Write(data, 0, data.Length);

        //Read
        var array1 = new byte[10];
        memStr.Position = 0;
        var gzipRd = new GZipStream(memStr, CompressionMode.Decompress);
        var res1 = gzipRd.Read(array1, 0, array1.Length); // => res1 = 0

        //Read
        var array2 = new byte[10];
        memStr.Position = 0;
        var res2 = memStr.Read(array2, 0, array2.Length); // => res2 = 10
    }

Solution

  • Try to use using.. and try like this:

        var memStr = new MemoryStream();
    
        ////Write
        var data = new byte[] { 0, 11, 22, 3, 4, 5, 6, 7, 8, 9 };
    
        using (GZipStream compressionStream = new GZipStream(memStr, CompressionMode.Compress))
        {
             compressionStream.Write(data, 0, data.Length);
        }
    
    
        ////Read
        var array1 = new byte[10];
        using (MemoryStream mem = new MemoryStream(memStr.ToArray()))
        using (GZipStream decompressionStream = new GZipStream(mem, CompressionMode.Decompress))
        {
             decompressionStream.Read(array1, 0, array1.Length);
        }