在C#中将.bz2流解压缩到文件

Man*_*ory 5 c# sharpziplib bzip2

我在尝试使用SharpZipLib库中的.bz2内容时遇到了麻烦,我无法在其他地方找到任何帮助.

任何帮助或建议将不胜感激,如果有人能指出我现有的解决方案,我可以从中学到这将是太棒了!

以下是我正在尝试做的事情,但显然它不起作用.目前我遇到的问题是在标记的行上未处理'EndOfStreamException'.代码有点混乱,我从来没有尝试过这样的事情......

正如你可以告诉我在解压缩之前从网上下载这个,我很确定部分代码可以正常工作.

while ((inputByte = responseStream.ReadByte()) != -1)
{
    using (MemoryStream ms = new MemoryStream())
    {
        using (BinaryWriter writer = new BinaryWriter(ms))
        {
            writer.Write((byte)inputByte);
        }

        using (BZip2InputStream unzip = new BZip2InputStream(ms)) //Exception occurs here
        {
            buffer = new byte[unzip.Length];
            unzip.Read(buffer, 0, buffer.Length);
        }

        using (FileStream fs = new FileStream(fPath, FileMode.OpenOrCreate, FileAccess.Write))
        {
            fs.Write(buffer, 0, buffer.Length);
        }

    }
}
Run Code Online (Sandbox Code Playgroud)

Jas*_*ted 3

您正在使用using语句。 using语句是编译器指令,用于try finally将 a 包裹在代码块中,并在执行IDisposible.Dispose()时调用。finally

长话短说,呼吁处置BinaryWriterBZip2InputStream并且FileStream可能会过早地处置父母MemoryStream

using尝试从其中删除三个块MemoryStream,看看是否可以解决您的问题。

编辑

BinaryWriter正在写一首单曲byteMemoryStream. 我不相信你需要一个方法来做到BinaryWriter这一点。MemoryStreamWriteByte()

然后你BZip2InputStream正在尝试从MemoryStream. 但MemoryStream它的位置位于流的末尾。没有数据可供读取,因此EndOfStreamException.