0

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
    }
all zoom
  • 13
  • 2
  • What, specifically, isn't working? And what changes have you made to your code in your attempts to get it working? And have you taken a look at the [GZipStream class documentation](https://learn.microsoft.com/en-us/dotnet/api/system.io.compression.gzipstream?view=netframework-4.8) ? – Jamie Taylor Jun 13 '19 at 11:04

2 Answers2

1

Thank you! This code also works, it seems I had to close gzipWr before reading:

    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 };
        using (var gzipWr = new GZipStream(memStr, CompressionMode.Compress, true))
            gzipWr.Write(data, 0, data.Length);

        //Read
        var array = new byte[10];
        memStr.Position = 0;
        using (var gzipRd = new GZipStream(memStr, CompressionMode.Decompress))
            gzipRd.Read(array, 0, array.Length); // => res = 10
    }
all zoom
  • 13
  • 2
0

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);
    }
TonyMkenu
  • 7,597
  • 3
  • 27
  • 49