Create new FileStream out of a byte array

前端 未结 3 1950
忘掉有多难
忘掉有多难 2021-01-13 19:04

I am attempting to create a new FileStream object from a byte array. I\'m sure that made no sense at all so I will try to explain in further detail below.

Tasks I am

3条回答
  •  星月不相逢
    2021-01-13 19:57

    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);
                }  
            }
        }
    }
    

提交回复
热议问题