Create new FileStream out of a byte array

前端 未结 3 1946
忘掉有多难
忘掉有多难 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:44

    It sounds like you need to use a MemoryStream.

    0 讨论(0)
  • 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);
                }  
            }
        }
    }
    
    0 讨论(0)
  • 2021-01-13 20:03

    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);
                            }
                        }
                    }
    
    0 讨论(0)
提交回复
热议问题