简体   繁体   中英

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. 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

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.

By the way, there is a static method to check the password of the Zip File:

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.

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 { }
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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