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

前端 未结 9 917
遥遥无期
遥遥无期 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);
    }
    
    0 讨论(0)
  • 2020-12-04 17:18

    If you still need it, you can use GZipStream constructor wit boolean argument (there are two such constructors) and pass true value there:

    tinyStream = new GZipStream(outStream, CompressionMode.Compress, true);
    

    In that case, when you close your tynyStream, your out stream will be still opened. Don't forget to copy data:

    mStream.CopyTo(tinyStream);
    tinyStream.Close();
    

    Now you've got memory stream outStream with zipped data

    Bugs and kisses for U

    Good luck

    0 讨论(0)
  • 2020-12-04 17:24
        public static byte[] compress(byte[] data)
        {
            using (MemoryStream outStream = new MemoryStream())
            {
                using (GZipStream gzipStream = new GZipStream(outStream, CompressionMode.Compress))
                using (MemoryStream srcStream = new MemoryStream(data))
                    srcStream.CopyTo(gzipStream);
                return outStream.ToArray();
            }
        }
    
        public static byte[] decompress(byte[] compressed)
        {
            using (MemoryStream inStream = new MemoryStream(compressed))
            using (GZipStream gzipStream = new GZipStream(inStream, CompressionMode.Decompress))
            using (MemoryStream outStream = new MemoryStream())
            {
                gzipStream.CopyTo(outStream);
                return outStream.ToArray();
            }
        }
    
    0 讨论(0)
提交回复
热议问题