C# 如何检查文件是否受密码保护&;用户传递的密码正确或未在c中使用dotnetzip#

C# 如何检查文件是否受密码保护&;用户传递的密码正确或未在c中使用dotnetzip#,c#,dotnetzip,C#,Dotnetzip,在我的应用程序中,我使用DotNetZip压缩和解压文件。 在提取文件之前,我想知道提供的密码是否正确。 现在我就是这样做的 foreach (var sourceFile in sourceFileNames) { ZipFile file = ZipFile.Read(sourceFile); foreach (ZipEntry entry in file.Entries) { if (FileSystem.Exists(conf.Target + entry.FileName)

在我的应用程序中,我使用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文件都有正确的密码,那么只提取它们。

也许您可以尝试:

我们通过扩展MemoryStream和重写 Write()方法

根据,DotNetZip代码将抛出 如果 密码不正确

因此,如果对Extract()的调用调用了Write()方法,那么 知道密码是否有效。下面是代码片段:


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

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

我根据我的要求更改了一些逻辑&它对我来说非常有效。对于小文件,可以使用Stream.Null(密码有效时不会引发异常)。请注意,此方法仅适用于版本1.9.1.8及更高版本。请注意,此方法仅适用于版本1.9.1.6及更高版本。
public static bool Ionic.Zip.ZipFile.CheckZipPassword(
    string zipFileName,
    string password
)