【问题标题】:Saving compressed memory stream to filestream , endfile is corrupted将压缩的内存流保存到文件流,endfile 已损坏
【发布时间】:2016-03-29 14:45:42
【问题描述】:

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

问题:
输出文件已损坏,我无法手动解压缩。使用记事本++,我也无法看到通常在 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");
    }

请有人更改问题以使其看起来更好。如果你愿意,可以添加更好的标题。谢谢。

【问题讨论】:

  • @Marko(我如何标记某人?)-(stackoverflow.com/questions/4214663/…
  • 认为您必须重置内存流位置。你的输出不是 0 字节长吗?
  • 我相信。我创建了流“输出”,所以 if 开头应该是 0 个字节。
  • @TamasHegedus 重置是指:output.Seek(0, SeekOrigin.Begin);
  • @TamasHegedus 成功了!我做了 TheStream.Position = 0;非常感谢。请添加对我的问题的回复,以便我将其标记为正确! :)

标签: c# stream 7zip sevenzipsharp


【解决方案1】:

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

这是一个修复:

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

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

TheStream.Position = 0;

【讨论】:

  • 非常感谢您的帮助。 :)
猜你喜欢
  • 1970-01-01
  • 2014-05-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-01-30
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多