简体   繁体   中英

C# MemoryStream Write method writing all 0's to byte array

I am trying to decompress a file using the GZipStream class. I use the GZipStream's CopyTo method to write the decompressed data to a MemoryStream object. After copying to the MemoryStream object, I can see the data is there by looking at the _buffer in the non-public properties.

The problems begin when I try to write to a byte array. Making the call to the Write() method results an a byte array full of 0's, as well as the _buffer property going to all 0's. I thought it might be a position or flush()/close() problem, but that does not solve it. Can someone tell me where I am going wrong?

var input = new MemoryStream(data);
var output = new MemoryStream();

using (var x = new System.IO.Compression.GZipStream(input, System.IO.Compression.CompressionMode.Decompress))
{
    x.CopyTo(output);
}

output.Position = 0;
var bytes = new byte[output.Length];

output.Write(bytes, 0, bytes.Length); //All 0's 
output.Flush();
output.Close(); //still all 0's 

You need to call Read not Write to get the data out.

output.Read(bytes, 0, bytes.Length);

You also could do

var bytes = output.ToArray();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM