using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Test { public class RAR { /// <summary> /// 解压缩Rar文件 /// </summary> /// <param name="rarFilePath">rar文件</param> /// <param name="unrarDestPath">解压到</param> public static void UnRarFile(string rarFilePath, string unrarDestPath) { //组合出需要shell的完整格式 string shellArguments = string.Format("x -o+ "{0}" "{1}\"", rarFilePath, unrarDestPath); //用Process调用 using (Process unrar = new Process()) { unrar.StartInfo.FileName = IOUtils.GetPhysicalPath("/ActiveX/WinRar.exe"); unrar.StartInfo.Arguments = shellArguments; //隐藏rar本身的窗口 unrar.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; unrar.Start(); //等待解压完成 unrar.WaitForExit(); unrar.Close(); } } /// <summary> /// 压缩一个或多个文件 /// </summary> /// <param name="rarFileName"></param> /// <param name="fileList"></param> /// <returns></returns> public static bool RarFileList(string rarFileName, string fileList) { bool returnVal = false; try { string shellArguments = string.Format("u -u -ep -ad "{0}" @"{1}"", rarFileName, fileList); ExecuteCommand(shellArguments); returnVal = true; } catch (Exception ex) { throw ex; } return returnVal; } /// <summary> /// 压缩一个目录 /// </summary> /// <param name="rarFileName"></param> /// <param name="dirPath"></param> /// <returns></returns> public static bool RarDirectory(string rarFileName, string dirPath) { bool returnVal = false; try { string shellArguments = string.Format("a -o+ -ep -ad "{0}" @"{1}"", rarFileName, dirPath); ExecuteCommand(shellArguments); returnVal = true; } catch (Exception ex) { throw ex; } return returnVal; } private static void ExecuteCommand(string CommandArguments) { using (Process rar_process = new Process()) { rar_process.StartInfo.FileName = IOUtils.GetPhysicalPath("/ActiveX/WinRar.exe"); rar_process.StartInfo.Arguments = CommandArguments; //隐藏rar本身的窗口 rar_process.StartInfo.WindowStyle = ProcessWindowStyle.Hidden; rar_process.StartInfo.UseShellExecute = false; try { rar_process.Start(); rar_process.WaitForExit(); string ex_message = ""; switch (rar_process.ExitCode) { case 0:// 成功操作。 ex_message = ""; break; case 1:// 警告。发生非致命错误。 ex_message = "警告。发生非致命错误。"; break; case 2:// 发生致命错误。 ex_message = "发生致命错误。"; break; case 3:// 解压时发生 CRC 错误。 ex_message = "解压时发生 CRC 错误。"; break; case 4:// 尝试修改一个 锁定的压缩文件。 ex_message = "尝试修改一个 锁定的压缩文件。"; break; case 5:// 写错误。 ex_message = "写错误。"; break; case 6:// 文件打开错误。 ex_message = "文件打开错误。"; break; case 7:// 错误命令行选项。 ex_message = "错误命令行选项。"; break; case 8:// 内存不足。 ex_message = "内存不足。"; break; case 9:// 文件创建错误。 ex_message = "文件创建错误。"; break; case 255:// 用户中断。 ex_message = "用户中断。"; break; } if (ex_message != string.Empty) throw new Exception(ex_message); } catch (Exception ex) { throw ex; } finally { rar_process.Close(); rar_process.Dispose(); } } } } }