user2478625
user2478625

Reputation: 131

Truncating data in decompress using GZipStream

I have compressed text data using below code

using (GZipStream zip = new GZipStream(ms, CompressionMode.Compress, true))
 {
     zip.Write(buffer, 0, buffer.Length);
 }

Now I am trying to decompress using below code but actual text is getting truncated if text is bigger. This is happening in .NET Core 6.0 but same code returning correct data if I use in .NET Framework 4.7.2

byte[] gzBuffer = Convert.FromBase64String(compressedText);
  using (MemoryStream ms = new MemoryStream())
  {
       int msgLength = BitConverter.ToInt32(gzBuffer, 0);
       ms.Write(gzBuffer, 4, gzBuffer.Length - 4);
       byte[] buffer = new byte[msgLength];
       ms.Position = 0;

       using (GZipStream zip = new GZipStream(ms, CompressionMode.Decompress))
       {
           zip.Read(buffer, 0, buffer.Length);
           zip.Close();
       }
       return Encoding.UTF8.GetString(buffer);
   }

What is reason of such behavior.

Upvotes: 0

Views: 320

Answers (1)

Charlieface
Charlieface

Reputation: 72298

The following code should work without any truncation

var gzBytes = Convert.FromBase64String(compressedText);
int msgLength = BitConverter.ToInt32(gzBuffer, 0);

using (var ms = new MemoryStream(gzBytes, 4, msgLength))
using (var zip = new GZipStream(ms, CompressionMode.Decompress))
using (var reader = new StreamReader(zip))
{
    return reader.ReadBlock();
}

This assumes that the first four bytes contain the number of bytes to read.

Upvotes: 0

Related Questions