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 文件位置的字符串)。我认为该代码对您非常有用。