简体   繁体   English

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

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

In My application I am using DotNetZip to Zip & UnZip files. 在我的应用程序中,我正在使用DotNetZip压缩和解压缩文件。 Before Extracting files I want to know if password provided is correct or not. 在提取文件之前,我想知道提供的密码是否正确。 Right now I am doing it like this. 现在,我正在这样做。

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);
 }
}

Here 'sourceFileNames' contains list of zip files 这里的“ sourceFileNames”包含zip文件列表

If password is wrong or not provided then then It will give error but I do not want to do Like this. 如果密码错误或未提供密码,那么它将给出错误,但我不想这样做。

What I want to do is first check passwords for each zip file & if all zip file has correct password then only extract them all. 我要做的是首先检查每个zip文件的密码,如果所有zip文件都具有正确的密码,则只提取所有密码。

By the way, there is a static method to check the password of the Zip File: 顺便说一句,有一种静态方法可以检查Zip文件的密码:

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

Perhaps you can try this solution : 也许您可以尝试以下解决方案

We solved this problem by extending MemoryStream and overriding the Write() method. 我们通过扩展MemoryStream并重写Write()方法解决了此问题。

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. 根据此处的论坛帖子 ,如果密码不正确,则在尝试ZipEntry的前几个字节后,DotNetZip代码将引发异常。

Therefore, if the call to Extract() ever calls our Write() method, we know the password worked. 因此,如果对Extract()的调用曾经调用我们的Write()方法,则我们知道该密码有效。 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 { }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM