如何使用 SevenZipSharp 提取多卷 7z 文件?

How to extract a multi volume 7z file using SevenZipSharp?

我使用 SevenZipSharp 库生成了多卷 7z 文件。

我遇到的问题是,当我尝试提取文件时,出现关于无效转换的异常:

Unable to cast object

of type 'SevenZip.InMultiStreamWrapper' to type 'SevenZip.InStreamWrapper'.

抛出异常的方法是SevenZipExtractor.Check().

这是用 Vb.Net 编写的示例代码,用于重现提取问题,但我也可以接受 C# 解决方案:

Public Overridable Function Extract(ByVal sourceFilePath As String,
                                    ByVal outputDirectorypath As String,
                                    ByVal password As String) As String

    If String.IsNullOrEmpty(password) Then
        Me.extractor = New SevenZipExtractor(sourceFilePath)
    Else
        Me.extractor = New SevenZipExtractor(sourceFilePath, password)
    End If

    ' Check for password matches doing an integrity check.
    If Me.extractor.Check() Then
        ' Start the extraction.
        Me.extractor.ExtractArchive(outputDirectorypath)

    Else
        Throw New Exception(
              "Failed to extract, maybe the provided password does not match?.")

    End If

    Return outputDirectorypath

End Function

如果我忽略完整性检查,使用设置了密码的多卷文件,那么我将无法提取它,因为会发生另一个异常...

可能是他们源代码中的错误,但我要求确定,因为库不支持提取多卷文件很奇怪...

Probablly is a bug in their source-code

确实是这样。

查看 SevenZipExtractor.cs 源代码,我们看到以下行(在方法 finally 块内,因此它始终执行):

((InStreamWrapper)_archiveStream).Dispose();

其中 _archiveStreamIInStream 类型的 class 字段(注意 I),它是一种不从 [=16= 派生的接口类型],因此没有 Dispose 方法。

更深入一点,我们可以看到它是用 InStreamWrapperInMultiStreamWrapper class 的实例初始化的。虽然它们共享共同的基础 class StreamWrapper,但后者不继承前者,因此出现强制转换异常。

如果你愿意修改源代码,修复它是很容易的。只需将上面的行替换为:

if (_archiveStream is IDisposable)
    ((IDisposable)_archiveStream).Dispose();

不过

If I ignore the integrity check, with a multi volume file that has a password set, then I cannot extract it because another exception occurs...

它们内部不会调用Check方法,调用ExtractArchive之前是否调用Check应该没有任何关系。所以我怀疑修复上述错误是否会阻止您正在谈论的另一个异常。