将压缩内存流保存到文件流,endfile已损坏

时间:2016-03-29 14:45:43

标签: c# stream 7zip sevenzipsharp

我使用seven.zip.sharp来压缩流。然后,我想在压缩完成后,将内存流中的数据保存到文件流中。该文件是“.7z”文件。

问题:
输出文件已损坏,我无法手动解压缩。使用notepad ++我也无法看到通常在7zip文件中找到的标题。

以下是代码:

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

请有人改变这个问题,让它看起来更好看。如果你愿意,可以添加更好的标题。谢谢。

1 个答案:

答案 0 :(得分:1)

因此,您计划将压缩流存储在临时MemoryBuffer中,然后将其写入文件。问题是在写入之后必须重置MemoryStream,因此读操作从头开始读取。如果输出文件的大小为0,那么我很确定这就是问题所在。

这是一个修复:

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

或者您可以将流声明为MemoryStream,并使用Position属性:

TheStream.Position = 0;