How do I use GZipStream with System.IO.MemoryStream?

前端 未结 9 996
遥遥无期
遥遥无期 2020-12-04 16:36

I am having an issue with this test function where I take an in memory string, compress it, and decompress it. The compression works great, but I can\'t seem to get the dec

9条回答
  •  粉色の甜心
    2020-12-04 17:17

    If you are attempting to use the MemoryStream (e.g. passing it into another function) but receiving the Exception "Cannot access a closed Stream." then there is another GZipStream constructor you can use that will help you.

    By passing in a true to the leaveOpen parameter, you can instruct GZipStream to leave the stream open after disposing of itself, by default it closes the target stream (which I didn't expect). https://msdn.microsoft.com/en-us/library/27ck2z1y(v=vs.110).aspx

    using (FileStream fs = File.OpenRead(f))
    using (var compressed = new MemoryStream())
    {
        //Instruct GZipStream to leave the stream open after performing the compression.
        using (var gzipstream = new GZipStream(compressed, CompressionLevel.Optimal, true))
            fs.CopyTo(gzipstream);
    
        //Do something with the memorystream
        compressed.Seek(0, SeekOrigin.Begin);
        MyFunction(compressed);
    }
    

提交回复
热议问题