首先需要安装7-Zip。7-Zip是一款高压缩比的压缩软件,不仅支持独有的7z文件格式,而且还支持各种其它压缩文件格式,其中包括 ZIP、RAR、CAB、GZIP、BZIP2和TAR等格式。此软件压缩的压缩比要比普通ZIP文件高30-50%。
方式一:
/// <summary>
/// 解压Zip文件
/// </summary>
public static void Unzip()
{
string zipFileName = @"E:\MyZip\Report.zip"; //需要被解压的Zip文件
string unZipPath = @"E:\MyZip\"; //解压后文件存放目录
string pwd = "123"; //解压密码
Process process = new Process();
process.StartInfo.FileName = @"C:\Program Files\7-Zip\7z.exe"; //7-Zip工具的运行程序
process.StartInfo.Arguments = String.Format("e \"{0}\" -p{1} -o\"{2}\"", zipFileName, pwd, unZipPath);
process.Start();
}
方式二:
创建ProcessHelper.cs类。
public class ProcessHelper
{
public static string[] ExecCommand(string commands)
{
//msg[0]执行结果;msg[1]错误结果
string[] msg = new string[2];
Process proc = new Process();
try
{
proc.StartInfo.FileName = "cmd.exe";
proc.StartInfo.UseShellExecute = false;
proc.StartInfo.RedirectStandardInput = true;
proc.StartInfo.RedirectStandardOutput = true;
proc.StartInfo.RedirectStandardError = true;
proc.StartInfo.CreateNoWindow = true;
proc.Start();
proc.StandardInput.WriteLine(commands);
proc.StandardInput.WriteLine("exit");
//执行结果
msg[0] = proc.StandardOutput.ReadToEnd();
proc.StandardOutput.Close();
//出错结果
msg[1] = proc.StandardError.ReadToEnd();
proc.StandardError.Close();
//超时等待
int maxWaitCount = 10;
while (proc.HasExited == false && maxWaitCount > 0)
{
proc.WaitForExit(1000);
maxWaitCount--;
}
if (maxWaitCount == 0)
{
msg[1] = "操作执行超时";
proc.Kill();
}
return msg;
}
catch (Exception ex)
{
msg[1] = "进程创建失败:";
msg[1] += ex.Message.ToString();
msg[1] += ex.StackTrace.ToString();
}
finally
{
proc.Close();
proc.Dispose();
}
return msg;
}
}
调用方法:
/// <summary>
/// 解压Zip文件
/// </summary>
public static void Unzip()
{
string zipExe = @"C:\Program Files\7-Zip\7z.exe"; //7-Zip工具的运行程序
string zipFileName = @"E:\MyZip\Report.zip"; //需要被解压的Zip文件
string unZipPath = @"E:\MyZip\"; //解压后文件存放目录
string pwd = "123"; //解压密码
//执行解压命令
string cmd = String.Format("\"{0}\" e \"{1}\" -p{2} -o\"{3}\"", zipExe, zipFileName, pwd, unZipPath);
ProcessHelper.ExecCommand(cmd);
}