使用DOTNETZIP验证zip文件的密码 [英] Validate the password for zip file using DOTNETZIP

查看:236
本文介绍了使用DOTNETZIP验证zip文件的密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何检查给定的密码是否正确以在运行时读取ZIP文件,如果密码错误,我必须显示错误警报消息.我对我的项目使用DotNetZip DLL.请给您建议的朋友. class ="h2_lin">解决方案

AFAIK,测试它的唯一方法是进行试验提取.如果提取成功,则密码正确.
如果不是,则密码不是.


我们通过扩展MemoryStream并重写Write()方法解决了此问题.

根据论坛帖子此处[http://dotnetzip.codeplex.com] 的说法,DotNetZip代码将在如果密码不正确,请尝试ZipEntry的前几个字节.

因此,如果对Extract()的调用曾经调用我们的Write()方法,则我们知道该密码有效.这是代码段:

 公共  class  ZipPasswordTester
{
    公共 布尔 CheckPassword(Ionic.Zip.ZipEntry条目,字符串密码)
    {
        尝试
        {
            使用( var  s =  PasswordCheckStream( ))
            {
                entry.ExtractWithPassword(s,密码);
            }
            返回 ;
        }
        捕获(Ionic.Zip.BadPasswordException)
        {
            返回 ;
        }
        捕获(PasswordCheckStream.GoodPasswordException)
        {
            返回 ;
        }
    }

    私有  PasswordCheckStream:System.IO.MemoryStream
    {
        公共 覆盖  void  Write(字节 []缓冲区, int 偏移量, int 计数)
        {
            抛出  GoodPasswordException();
        }
        
        公共  GoodPasswordException:System.Exception {}
    }
} 


How to check the given password is correct or not for read the ZIP file at run time, If its wrong password i have to show error alert message.I using DotNetZip DLL for my project.Please Give your suggestion friends.

解决方案

AFAIK, the only way to test it is to do a trial extraction. If it extracts ok, the password is fine.
If it doesn''t, the password is not.


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

According to the forum post here [http://dotnetzip.codeplex.com], 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 { }
    }
}


这篇关于使用DOTNETZIP验证zip文件的密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆