SoFunction
Updated on 2025-03-07

Methods of C# calling WinRAR in Windows system to compress and decompress files

The process descriptions are all in the comments, let's look at the code directly:
compression:

using System;

using ;

using ;

using ;

using ;

using ;

using ;

public class winrar

{
  #region compressed files
  /// <summary>

  /// Compress files
  /// </summary>

  /// <param name="filesPath">Compressed file and full path (D:\abc)</param>
  /// <param name="zipFilePath">The complete path stored in the compressed package (D:\or d:\)</param>
  public static void CreateZipFile(string filesPath, string zipFilePath)

  {

    if (!(filesPath))

    {

      ("Cannot find directory '{0}'", filesPath);

      return;

    }

    try

    {

      string[] filenames = (filesPath);

      using (ZipOutputStream s = new ZipOutputStream((zipFilePath)))

      {

        (9); // Compression level 0-9
        // = "123"; //Zip compressed file password
        byte[] buffer = new byte[4096]; //Buffer size
        foreach (string file in filenames)

        {

          ZipEntry entry = new ZipEntry((file));

           = ;

          (entry);

          using (FileStream fs = (file))

          {

            int sourceBytes;

            do

            {

              sourceBytes = (buffer, 0, );

              (buffer, 0, sourceBytes);

            } while (sourceBytes &gt; 0);

          }

        }

        ();

        ();

      }

    }

    catch (Exception ex)

    {

      (ex, "The Error in Compression File!");

    }

  }

  #endregion

  #region Unzip the file
  /// &lt;summary&gt;

  /// Unzip the file
  /// &lt;/summary&gt;

  /// <param name="zipFilePath">Decompress the file and the full path (d:\or d:\)</param>
  public static void UnZipFile(string zipFilePath)

  {

    if (!(zipFilePath))

    {

      ("Cannot find file '{0}'", zipFilePath);

      return;

    }

    using (ZipInputStream s = new ZipInputStream((zipFilePath)))

    {

      ZipEntry theEntry;

      while ((theEntry = ()) != null)

      {

        ();

        string directoryName = ();

        string fileName = ();

        // create directory

        if ( &gt; 0)

        {

          (directoryName);

        }

        if (fileName != )

        {

          using (FileStream streamWriter = ())

          {

            int size = 2048;

            byte[] data = new byte[2048];

            while (true)

            {

              size = (data, 0, );

              if (size &gt; 0)

              {

                (data, 0, size);

              }

              else

              {

                break;

              }

            }

          }

        }

      }

    }

  }

  #endregion


string rarFile=@"C:\Program Files\WinRAR\";//The path where winrar is located, find the folder where the execution file is located and "C:\Program Files\WinRAR\

 #region RAR compressed file (supported paths containing spaces)
 /// &lt;summary&gt;

  /// Compress to .rar
  /// &lt;/summary&gt;

  /// <param name="intputPath">Input directory</param>
  /// <param name="outputPath">Output directory</param>
  /// <param name="outputFileName">Output file name</param>
 

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

  {

    //Rar commands and parameters when executing
    string rarCmd;

    //System of starting process
    ProcessStartInfo processStartInfo;

    //Process Object
    Process process;

 //Command Parameters
 rarCmd = " a " + outputFileName + " " + intputPath + " -r -ep1";

 //rar path
 string rarFile =  + @"\";

 if ((' ') &gt; 0 || (' ') &gt; 0)

 {

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

 }

 if (!( + @"\"))

 { 

  rarFile=@"C:\Program Files\WinRAR\";

 }

    try

    {

      

      //Judge whether the input directory exists
      if (!(intputPath))

      {

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

      }

      

      //Create parameters to start the process
      processStartInfo = new ProcessStartInfo();

      //Specify the startup file name
       = @"C:\Program Files\WinRAR\";

      //Specify the commands and parameters when starting the file
       = rarCmd;

      //Specify the startup window mode: Hide
       = ;

      //Specify the path to reach after compression
       = outputPath;

      //Create process object
      process = new Process();

      //Specify the process object startup information object
       = processStartInfo;

      //Start the process
      ();

      //Specify the process to revoke itself
      ();

    }

    catch (Exception ex)

    {

      throw ex;

    }

  }

 #endregion

 #region RAR decompression file (support path contains spaces)
 /// &lt;summary&gt;

 /// Unzip the file
 /// &lt;/summary&gt;

 /// <param name="outputPath">Decompressed path</param>
 /// <param name="inputPath">Path where the compressed package is located (the decompression path must exist)</param>
 /// <param name="inputFileName">Compressed package name</param>
 /// &lt;returns&gt;&lt;/returns&gt;

 

 public static void DecompressRar(string outputPath, string inputPath, string inputFileName)

 {

 //Rar commands and parameters when executing
 string rarCmd;

 //System of starting process
 ProcessStartInfo processStartInfo;

 //Process Object
 Process process;

 //rar path
 string rarFile = + @"\" ;

 //Command Parameters
 rarCmd = " e " + inputFileName + " " + outputPath + " -r -ep1";

 if ((' ') &gt; 0 || (' ') &gt; 0)

 {

  rarCmd = "x -inul -y -o+ -ep1 \"" + inputPath + "\\" + inputFileName + "\" \"" + outputPath+"\"";

 }

 if (!( + @"\"))

 { 

  rarFile=@"C:\Program Files\WinRAR\";

 }

 try

 {

  //Create parameters to start the process
  processStartInfo = new ProcessStartInfo();

  //Specify the startup file name
   = rarFile;

  //Specify the commands and parameters when starting the file
   = rarCmd;

  //Specify the startup window mode: Hide
   = ;

  //Specify the path to reach after decompression (the folder needs to exist)
   = inputPath;

  //Create process object
  process = new Process();

  //Specify the process object startup information object
   = processStartInfo;

  //Start the process
  ();

  //Specify the process to revoke itself
  ();

  //Release resources
  ();

 }

 catch (Exception ex)

 {

  throw ex;

 }

 }

 #endregion

}

Unzip:

class UseWinRar 
  { 
    private string rarExeFile = null;//path    private bool useAble = false;//Is the flag WinRar available 
    public UseWinRar()//Construction method    { 
      rarExeFile = getRarExe(); 
      useAble = !(rarExeFile);//If the path is not empty, it means it is available    } 
 
    public static string getRarExe()//Get the disk path where WinRar is located    { 
      string rarExe = null; 
      RegistryKey regKey = (@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\"); 
      if (regKey == null) 
      { 
        return null; 
      } 
      rarExe = ("").ToString(); 
      ();//Close the registry      return rarExe; 
    } 
 
    public bool exeRarCmd(string cmd)//Execute a command    { 
      if (!useAble) 
      { 
        return false; 
      } 
      Process process = new Process();// Create a new process      ProcessStartInfo startInfo = new ProcessStartInfo(rarExeFile);// Create a new startup information       = cmd;//Set the execution parameters of startup information      // = workDirectory;//Set the working directory for startup information       = ;//Set the program background to run       = startInfo;//Setting process startup information      ();//Start the process      return true; 
    } 
 
    public bool unZipAll(string zipFile, string targetDirectory)//Decompress the specified compressed file to the specified directory    { 
      if (! (zipFile)) 
      { 
        return false; 
      } 
      string zipCmd = "x " + zipFile +" "+ targetDirectory + " -y -ibck";//Decompress all files in the compressed file in the background to the specified directory      exeRarCmd(zipCmd);//Execute the decompression operation      return true; 
    } 
 
    public bool unZipToCurrentDirectory(string zipFile)//Decompress the compressed file to the current directory    { 
      if (!(zipFile)) 
      { 
        return false; 
      } 
      FileInfo fileInfo = new FileInfo(zipFile); 
      return unZipAll(zipFile, ); 
    } 
  } 
  
Main:
public static void Main() 
    { 
      UseWinRar rar = new UseWinRar(); 
      string[] zipFiles = (, "*.zip");//Get all zip file paths      foreach (string zipFile in zipFiles) 
      { 
        (zipFile); 
      } 
    }