如何在 C# 中使用 dotnetzip 检查文件是否受密码保护以及用户传递的密码是否正确

How to check if file is password protected & password passed by user is correct or not using dotnetzip in c#

在我的应用程序中,我使用 DotNetZip 压缩和解压缩文件。 在提取文件之前,我想知道提供的密码是否正确。 我现在就是这样做的。

foreach (var sourceFile in sourceFileNames) {
 ZipFile file = ZipFile.Read(sourceFile);
 foreach (ZipEntry entry in file.Entries) {
    if (FileSystem.Exists(conf.Target + entry.FileName)) {
       FileSystem.Delete(conf.Target + entry.FileName);
    }
    if (!string.IsNullOrEmpty(conf.Password)) {
       entry.Password = conf.Password;
    }
       entry.Extract(conf.Target);
 }
}

此处 'sourceFileNames' 包含 zip 文件列表

如果密码错误或未提供,那么它会报错,但我不想这样做。

我想做的是首先检查每个 zip 文件的密码,如果所有 zip 文件都有正确的密码,那么只提取它们。

也许你可以试试this solution:

We solved this problem by extending MemoryStream and overriding the Write() method.

According to the forum post here, the DotNetZip code will throw an exception after trying the first few bytes of the ZipEntry if the password is incorrect.

Therefore, if the call to Extract() ever calls our Write() method, we know the password worked. Here's the code snippet:

public class ZipPasswordTester
{
    public bool CheckPassword(Ionic.Zip.ZipEntry entry, string password)
    {
        try
        {
            using (var s = new PasswordCheckStream())
            {
                entry.ExtractWithPassword(s, password);
            }
            return true;
        }
        catch (Ionic.Zip.BadPasswordException)
        {
            return false;
        }
        catch (PasswordCheckStream.GoodPasswordException)
        {
            return true;
        }
    }

    private class PasswordCheckStream : System.IO.MemoryStream
    {
        public override void Write(byte[] buffer, int offset, int count)
        {
            throw new GoodPasswordException();
        }

        public class GoodPasswordException : System.Exception { }
    }
}

顺便说一句,有一个静态方法可以检查Zip文件的密码:

public static bool Ionic.Zip.ZipFile.CheckZipPassword(
    string zipFileName,
    string password
)