Windows系统中C#调用WinRAR来压缩和解压缩文件的方法

2019-12-30 12:00:11丽君

 

   string rarFile=@"C:Program FilesWinRARWinRAR.exe";//winrar之所在的路径,这里找执行文件所在文件夹和"C:Program FilesWinRARWinRAR.exe


 #region RAR压缩文件(支持路径中含有空格)

 /// <summary>

  /// 压缩到.rar

  /// </summary>

  /// <param name="intputPath">输入目录</param>

  /// <param name="outputPath">输出目录</param>

  /// <param name="outputFileName">输出文件名</param>

 

  public static void CompressRar(string intputPath, string outputPath, string outputFileName)

  {

    //rar 执行时的命令、参数

    string rarCmd;

    //启动进程的参数

    ProcessStartInfo processStartInfo;

    //进程对象

    Process process;

 //命令参数

 rarCmd = " a " + outputFileName + " " + intputPath + " -r -ep1";

 //rar路径

 string rarFile = System.Windows.Forms.Application.StartupPath + @"rar.exe";

 if (outputPath.IndexOf(' ') > 0 || intputPath.IndexOf(' ') > 0)

 {

  rarCmd = " a " + outputFileName + " "" + intputPath + "" -r -ep1";

 }

 if (!File.Exists(System.Windows.Forms.Application.StartupPath + @"rar.exe"))

 { 

  rarFile=@"C:Program FilesWinRARWinRAR.exe";

 }

    try

    {

      

      //判断输入目录是否存在

      if (!Directory.Exists(intputPath))

      {

        throw new ArgumentException("CompressRar'arge : inputPath isn't exsit.");

      }

      

      //创建启动进程的参数

      processStartInfo = new ProcessStartInfo();

      //指定启动文件名

      processStartInfo.FileName = @"C:Program FilesWinRARWinRAR.exe";

      //指定启动该文件时的命令、参数

      processStartInfo.Arguments = rarCmd;

      //指定启动窗口模式:隐藏

      processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

      //指定压缩后到达路径

      processStartInfo.WorkingDirectory = outputPath;

      //创建进程对象

      process = new Process();

      //指定进程对象启动信息对象

      process.StartInfo = processStartInfo;

      //启动进程

      process.Start();

      //指定进程自行退行为止

      process.WaitForExit();

    }

    catch (Exception ex)

    {

      throw ex;

    }

  }

 #endregion

 #region RAR解压文件(支持路径中含有空格)

 /// <summary>

 /// 解压文件

 /// </summary>

 /// <param name="outputPath">解压到的路径</param>

 /// <param name="inputPath">压缩包所在路径(解压路径需存在)</param>

 /// <param name="inputFileName">压缩包名</param>

 /// <returns></returns>