现在让我们认为我们有一个随机的zip文件,所以我怎么知道该文件受密码保护?因为没有像这样的方法
bool IsPasswordProtected(string fileName);
我问这个原因有几种方法从zip文件中提取条目但我仍然要使用Extract()或ExtractWithPassword()但是要使用它我必须知道我要提取的文件实际上是密码受保护与否。我知道密码适用于不是zip文件本身的条目。我检查了文档中的每个方法,但是我找不到合适的方法来解决这个问题或者我错过了什么?
谢谢。!
检查ZipEntry.UsesEncryption
财产。
我会尝试ZipEntry.Extract
方法,如果由于错过密码而失败,你会得到一个例外,然后尝试ExtractWithPassword
,看看是否有效。如果它不起作用,则失败并返回原始异常。不幸的是,Password
属性是只写的。
根据文档ZipEntry.UsesEntryption
与要求密码不同。
ZipFile zip = ZipFile.Read(zipFileName);
if (!password.Equals(""))
{
zip.Password = password;
}
try
{
if (Directory.Exists(outputDirectory))
{
Directory.Delete(outputDirectory);
}
Directory.CreateDirectory(outputDirectory);
zip.ExtractAll(outputDirectory);
System.Windows.Forms.MessageBox.Show("Unzip process is complete.", "Information");
}
catch (BadPasswordException e)
{
string value = "Type password for unzip";
if (InputBox("Zip file was password protected.", "Password : ",ref value ) == System.Windows.Forms.DialogResult.OK)
{
ExtractFileToDirectory(filename, outputpath,value);
}
}
而InputBox方法如下......
public DialogResult InputBox(string title, string promptText, ref string value)
{
Form form = new Form();
System.Windows.Forms.Label label = new System.Windows.Forms.Label();
System.Windows.Forms.TextBox textBox = new System.Windows.Forms.TextBox();
System.Windows.Forms.Button buttonOk = new System.Windows.Forms.Button();
System.Windows.Forms.Button buttonCancel = new System.Windows.Forms.Button();
form.Text = title;
label.Text = promptText;
textBox.Text = value;
buttonOk.Text = "OK";
buttonCancel.Text = "Cancel";
buttonOk.DialogResult = System.Windows.Forms.DialogResult.OK;
buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel;
label.SetBounds(9, 20, 372, 13);
textBox.SetBounds(12, 36, 372, 20);
buttonOk.SetBounds(228, 72, 75, 23);
buttonCancel.SetBounds(309, 72, 75, 23);
label.AutoSize = true;
textBox.Anchor = textBox.Anchor | AnchorStyles.Right;
buttonOk.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
buttonCancel.Anchor = AnchorStyles.Bottom | AnchorStyles.Right;
form.ClientSize = new System.Drawing.Size(396, 107);
form.Controls.AddRange(new System.Windows.Forms.Control[] { label, textBox, buttonOk, buttonCancel });
form.ClientSize = new System.Drawing.Size(Math.Max(300, label.Right + 10), form.ClientSize.Height);
form.FormBorderStyle = FormBorderStyle.FixedDialog;
form.StartPosition = FormStartPosition.CenterScreen;
form.MinimizeBox = false;
form.MaximizeBox = false;
form.AcceptButton = buttonOk;
form.CancelButton = buttonCancel;
DialogResult dialogResult = form.ShowDialog();
value = textBox.Text;
return dialogResult;
}
当zip文件有密码时,代码很有用。如果zip文件有密码,则会出现输入文本对话框并提取密码。请注意(outputDirectory是用于提取zip文件位置的字符串)。我认为该代码对您非常有用。
我也有同样的问题。我尝试了Francis Upton的代码。它没用。你可以试试
ZipFile.CheckZipPassword(TemporaryFilePath, PassWord);
使PassWord为null;就像......
bool ExistPassWord = ZipFile.CheckZipPassword(TemporaryFilePath, null);