【问题标题】:file stream exception on reading zip file (how to use using block)读取 zip 文件时的文件流异常(如何使用块)
【发布时间】:2016-04-09 20:36:55
【问题描述】:

我正在使用 SharpCompress 库(这不是问题)。我的拉链要么未受保护,要么受密码保护(都使用相同的密码)。所以我是这样编码的:

using(Stream stream = File.OpenRead(file))
{
    try {
        reader = ZipReader.Open(stream);
        moreFiles = reader.MoveToNextEntry();
    } catch (Exception e) {
        reader = ZipReader.Open(stream, pwd);
        moreFiles = reader.MoveToNextEntry();
    }
    //rest of code
}

每当它到达 catch 块调用 MoveToNextEntry 时,它总是会引发一个模糊的“无效标头:xxxxxxxx”异常,因为我认为流不在开始处。

我不能将File.OpenRead(file) 放入异常中,因为我正在使用using 块。如果我使用(如 cmets 中所建议的)搜索,我会得到一个未设置的对象引用(可能已调用 dispose)。

有没有办法重置这个文件流并仍然确保它被释放(同时仍然使用using 块)。我不知道再次调用 open 是否会导致 using 块也有点不高兴。

谢谢。

【问题讨论】:

    标签: c# sharpcompress


    【解决方案1】:

    您是否尝试过以下方法:

    try
    {
        reader = ZipReader.Open(stream);
        moreFiles = reader.MoveToNextEntry();
    }
    catch (CryptographicException e) when (e.Message == "No password supplied for encrypted zip.")
    {
        stream.Seek(0, SeekOrigin.Begin);
        reader = ZipReader.Open(stream, pwd);
        moreFiles = reader.MoveToNextEntry();
    }
    

    【讨论】:

    • 我得到一个未设置对象引用的异常。大概那个 dispose 已经被调用了?
    • 我刚刚使用 SharpCompress 0.11.5 进行了尝试,并且成功了。我正在使用我尝试过的完整代码更新答案。我还编辑了 catch 语句来处理密码保护异常。如果您不在 C# 6.0 中,则可以省略 when 指令。
    • 谢谢 :) 我想我后来错过了公开赛。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-02-23
    • 1970-01-01
    • 1970-01-01
    • 2017-03-24
    • 2019-04-10
    • 2021-12-15
    相关资源
    最近更新 更多