Create new FileStream out of a byte array

ε祈祈猫儿з 提交于 2019-12-01 07:16:56

Since you don't know how many bytes you'll be reading from the GZipStream, you can't really allocate an array for it. You need to read it all into a byte array and then use a MemoryStream to decompress.

const int BufferSize = 65536;
byte[] compressedBytes = File.ReadAllBytes("compressedFilename");
// create memory stream
using (var mstrm = new MemoryStream(compressedBytes))
{
    using(var inStream = new GzipStream(mstrm, CompressionMode.Decompress))
    {
        using (var outStream = File.Create("outputfilename"))
        {
            var buffer = new byte[BufferSize];
            int bytesRead;
            while ((bytesRead = inStream.Read(buffer, 0, BufferSize)) != 0)
            {
                outStream.Write(buffer, 0, bytesRead);
            }  
        }
    }
}

It sounds like you need to use a MemoryStream.

Here is what I ended up doing. I realize that I did not give sufficient information in my question - and I apologize for that - but I do know the size of the file I need to decompress as I am using it earlier in my program. This buffer is referred to as "blen".

string fi = @"C:\Path To Compressed File";
    // Get the stream of the source file.
           //     using (FileStream inFile = fi.OpenRead())
                using (MemoryStream infile1 = new MemoryStream(File.ReadAllBytes(fi)))
                {

                    //Create the decompressed file.
                    string outfile = @"C:\Decompressed.exe";
                    {
                        using (GZipStream Decompress = new GZipStream(infile1,
                                CompressionMode.Decompress))
                        {
                            byte[] b = new byte[blen.Length];
                            Decompress.Read(b,0,b.Length);
                            File.WriteAllBytes(outfile, b);
                        }
                    }
                }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!