Search code examples
c#stream7zipsevenzipsharp

Saving compressed memory stream to filestream , endfile is corrupted


i am using seven.zip.sharp to compress a stream. I then want to after the compression is done, save the data in the memory stream to a filestream. The file being a ".7z" file.

Problem:
The output file is corrupted and i am unable to decompress it manually. Using notepad++ i am also unable to see the header that is normally found in a 7zip file.

Here is the code:

    //Memory stream used to store compressed stream
    public System.IO.Stream TheStream = new System.IO.MemoryStream();

    //Start compress stream
    private void button1_Click(object sender, EventArgs e)
    {
        Thread newThread1 = new Thread(this.COMP_STREAM);
        newThread1.Start();
    }

    //See size of stream on demand
    private void button2_Click(object sender, EventArgs e)
    {
            textBox1.Clear();
            textBox1.Text += "-" + TheStream.Length;
    }

    //To Create file
    private void button3_Click(object sender, EventArgs e)
    {


        byte[] buffer = new byte[1024]; // Change this to whatever you need

        using (System.IO.FileStream output = new FileStream(@"F:\Pasta desktop\sss\TESTEmiau.7z", FileMode.Create))
        {
            int readBytes = 0;
            while ((readBytes = TheStream.Read(buffer, 0, buffer.Length)) > 0)
            {
                output.Write(buffer, 0, readBytes);
            }
            output.Close();
        }
        MessageBox.Show("DONE");
    }

    //To compress stream
    public void COMP_STREAM()
    {
        SevenZip.SevenZipCompressor.SetLibraryPath(@"C:\Program Files\7-Zip\7z.dll");
        var stream = System.IO.File.OpenRead(@"F:\Pasta desktop\sss\lel.exe");

        SevenZip.SevenZipCompressor compressor = new SevenZip.SevenZipCompressor();
        compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2;
        compressor.CompressionLevel = SevenZip.CompressionLevel.Ultra;
        compressor.CompressStream(stream, TheStream); //I know i can just use a FileStream here but i am doing this from testing only.
        MessageBox.Show("Done");
    }

Please someone alter the question to make it look better. And add better title to if u desire. Thank you.


Solution

  • So you planned to store the compressed stream in a temporary MemoryBuffer, and later write it out to a file. The problem is that the MemoryStream must be reset after the write, so the read operation reads from the beginning. If your output file is of size 0, then I'm pretty sure that this is the problem.

    Here is a fix:

    // Seek the beginning of the `MemoryStrem` before writing it to a file:
    TheStream.Seek(0, SeekOrigin.Begin);
    

    Or you can declare the stream to be a MemoryStream, and use the Position property:

    TheStream.Position = 0;