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

  • 2021-09-16 07:47:39
  • OfStack

The process instructions are all in the comments, so let's look at the code directly:
Compression:


using System;

using System.Collections.Generic;

using System.Linq;

using System.Text;

using System.IO;

using ICSharpCode.SharpZipLib.Zip;

using System.Diagnostics;

public class winrar

{
  #region  Zip file 

  /// <summary>

  ///  Zip file 

  /// </summary>

  /// <param name="filesPath"> Compressed file and full path (D:\abc)</param>

  /// <param name="zipFilePath"> The full path stored in the compressed packet (D:\a.zip Or d:\a.rar)</param>

  public static void CreateZipFile(string filesPath, string zipFilePath)

  {

    if (!Directory.Exists(filesPath))

    {

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

      return;

    }

    try

    {

      string[] filenames = Directory.GetFiles(filesPath);

      using (ZipOutputStream s = new ZipOutputStream(File.Create(zipFilePath)))

      {

        s.SetLevel(9); //  Compression level  0-9

        //s.Password = "123"; //Zip Compressed file password 

        byte[] buffer = new byte[4096]; // Buffer size 

        foreach (string file in filenames)

        {

          ZipEntry entry = new ZipEntry(Path.GetFileName(file));

          entry.DateTime = DateTime.Now;

          s.PutNextEntry(entry);

          using (FileStream fs = File.OpenRead(file))

          {

            int sourceBytes;

            do

            {

              sourceBytes = fs.Read(buffer, 0, buffer.Length);

              s.Write(buffer, 0, sourceBytes);

            } while (sourceBytes > 0);

          }

        }

        s.Finish();

        s.Close();

      }

    }

    catch (Exception ex)

    {

      AutoCompare.ErrorLog.SaveError(ex, " Error compressing file! ");

    }

  }

  #endregion

  #region  Extract a file 

  /// <summary>

  ///  Extract a file 

  /// </summary>

  /// <param name="zipFilePath"> Unzip file and full path (d:\a.zip Or d:\a.rar)</param>

  public static void UnZipFile(string zipFilePath)

  {

    if (!File.Exists(zipFilePath))

    {

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

      return;

    }

    using (ZipInputStream s = new ZipInputStream(File.OpenRead(zipFilePath)))

    {

      ZipEntry theEntry;

      while ((theEntry = s.GetNextEntry()) != null)

      {

        Console.WriteLine(theEntry.Name);

        string directoryName = Path.GetDirectoryName(theEntry.Name);

        string fileName = Path.GetFileName(theEntry.Name);

        // create directory

        if (directoryName.Length > 0)

        {

          Directory.CreateDirectory(directoryName);

        }

        if (fileName != String.Empty)

        {

          using (FileStream streamWriter = File.Create(theEntry.Name))

          {

            int size = 2048;

            byte[] data = new byte[2048];

            while (true)

            {

              size = s.Read(data, 0, data.Length);

              if (size > 0)

              {

                streamWriter.Write(data, 0, size);

              }

              else

              {

                break;

              }

            }

          }

        }

      }

    }

  }

  #endregion


string rarFile = @ "C:\ Program Files\ WinRAR\ WinRAR.exe"; The path to//winrar, where you can find the folder where the executable files are located and "C:\ Program Files\ WinRAR\ WinRAR. exe


 #region RAR Compressed file (supported path with spaces) 

 /// <summary>

  ///  Compress to .rar

  /// </summary>

  /// <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, parameters at execution time 

    string rarCmd;

    // Parameters for starting the process 

    ProcessStartInfo processStartInfo;

    // Process object 

    Process process;

 // Command parameters 

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

 //rar Path 

 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 Files\WinRAR\WinRAR.exe";

 }

    try

    {

      

      // Determining whether the input directory exists 

      if (!Directory.Exists(intputPath))

      {

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

      }

      

      // Create parameters to start the process 

      processStartInfo = new ProcessStartInfo();

      // Specify the startup file name 

      processStartInfo.FileName = @"C:\Program Files\WinRAR\WinRAR.exe";

      // Specify the command when starting the file, parameters 

      processStartInfo.Arguments = rarCmd;

      // Specify the startup window mode: hide 

      processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

      // Specify the compressed arrival path 

      processStartInfo.WorkingDirectory = outputPath;

      // Create a process object 

      process = new Process();

      // Specify the process object startup information object 

      process.StartInfo = processStartInfo;

      // Start process 

      process.Start();

      // Specifies that the process retrogresses itself 

      process.WaitForExit();

    }

    catch (Exception ex)

    {

      throw ex;

    }

  }

 #endregion

 #region RAR Unzip file (support path with spaces) 

 /// <summary>

 ///  Extract a file 

 /// </summary>

 /// <param name="outputPath"> Path unzipped to </param>

 /// <param name="inputPath"> Path where the compressed packet is located (decompression path needs to exist) </param>

 /// <param name="inputFileName"> Compressed package name </param>

 /// <returns></returns>


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

 {

 //rar  Commands, parameters at execution time 

 string rarCmd;

 // Parameters for starting the process 

 ProcessStartInfo processStartInfo;

 // Process object 

 Process process;

 //rar Path 

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

 // Command parameters 

 rarCmd = " e " + inputFileName + " " + outputPath + " -r -ep1";

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

 {

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

 }

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

 { 

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

 }

 try

 {

  // Create parameters to start the process 

  processStartInfo = new ProcessStartInfo();

  // Specify the startup file name 

  processStartInfo.FileName = rarFile;

  // Specify the command when starting the file, parameters 

  processStartInfo.Arguments = rarCmd;

  // Specify the startup window mode: hide 

  processStartInfo.WindowStyle = ProcessWindowStyle.Hidden;

  // Specify the unzipped arrival path (folder needs to exist) 

  processStartInfo.WorkingDirectory = inputPath;

  // Create a process object 

  process = new Process();

  // Specify the process object startup information object 

  process.StartInfo = processStartInfo;

  // Start process 

  process.Start();

  // Specifies that the process retrogresses itself 

  process.WaitForExit();

  // Release resources 

  process.Close();

 }

 catch (Exception ex)

 {

  throw ex;

 }

 }

 #endregion

}

Decompression:


class UseWinRar 
  { 
    private string rarExeFile = null;//WinRar.exe Path  
    private bool useAble = false;// Sign WinRar Available  
 
    public UseWinRar()// Construction method  
    { 
      rarExeFile = getRarExe(); 
      useAble = !string.IsNullOrEmpty(rarExeFile);// If WinRar.exe The path is not empty, indicating that it is available  
    } 
 
    public static string getRarExe()// Get WinRar Disk path on which  
    { 
      string rarExe = null; 
      RegistryKey regKey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\WinRAR.exe"); 
      if (regKey == null) 
      { 
        return null; 
      } 
      rarExe = regKey.GetValue("").ToString(); 
      regKey.Close();// Close the registry  
      return rarExe; 
    } 
 
    public bool exeRarCmd(string cmd)// Execute a command  
    { 
      if (!useAble) 
      { 
        return false; 
      } 
      Process process = new Process();// New 1 Process  
      ProcessStartInfo startInfo = new ProcessStartInfo(rarExeFile);// New 1 Startup information  
      startInfo.Arguments = cmd;// Set the execution parameters of startup information  
      //startInfo.WorkingDirectory = workDirectory;// Set the working directory of startup information  
      startInfo.WindowStyle = ProcessWindowStyle.Hidden;// Set the program to run in the background  
      process.StartInfo = startInfo;// Set up the startup information of the procedure  
      process.Start();// Start process  
      return true; 
    } 
 
    public bool unZipAll(string zipFile, string targetDirectory)// Unzip the specified compressed file to the specified directory  
    { 
      if (! File.Exists(zipFile)) 
      { 
        return false; 
      } 
      string zipCmd = "x " + zipFile +" "+ targetDirectory + " -y -ibck";// Decompress all files in the compressed file to the specified directory in the background  
      exeRarCmd(zipCmd);// Perform an unzip operation  
      return true; 
    } 
 
    public bool unZipToCurrentDirectory(string zipFile)// Unzip the compressed file to the current directory  
    { 
      if (!File.Exists(zipFile)) 
      { 
        return false; 
      } 
      FileInfo fileInfo = new FileInfo(zipFile); 
      return unZipAll(zipFile, fileInfo.DirectoryName); 
    } 
  } 
  
Main:
public static void Main() 
    { 
      UseWinRar rar = new UseWinRar(); 
      string[] zipFiles = Directory.GetFiles(Environment.CurrentDirectory, "*.zip");// Get all zip File path  
      foreach (string zipFile in zipFiles) 
      { 
        rar.unZipToCurrentDirectory(zipFile); 
      } 
    } 


Related articles: