SoFunction
Updated on 2025-03-07

C# compression or decompression rar and zip file method examples

Preface

In order to facilitate the transmission and storage of files on the network, files are usually compressed. Commonly used compression formats include rar, zip and 7z. This article will introduce how to compress and decompress these types of files in C#, and provide some open source libraries for decompressing files in C#.

Compress and decompress rar files in C#.NET

rar format is a compression format with patented files, a commercial compression format, not open source, and is public for decoding algorithms, but the compression algorithm is private and requires payment. If you need to use rar format for decompression in your commercial software, then you need to pay for rar. rar is very popular in China because of the existence of piracy. Because the algorithm is not open source, we have no third-party open source libraries to choose from for compressing rar, so we can only find another way out.

For rar decompression, we usually use winrar. Almost every machine has winrar installed. For ordinary users, it provides a decompression method based on user interface. In addition, it also provides a command line decompression method, which provides an entry for us to decompress the rar format in the program. We can call rar command line program in C# program to implement decompression. The idea is as follows:

1. Determine the registry to confirm whether the user machine has installed the winrar program. If installed, retrieve the winrar installation directory.

2. Create a command line execution process.

3. Decompression is achieved through winrar's command line parameters.

First, we use the following code to determine whether the user's computer has the winrar compression tool installed:

If winrar has been installed, you can return the installation location of winrar through the following code. If it is not installed, it will return an empty string and finally close the registry:

public static string ExistsWinRar()
{
    string result = ;

    string key = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
    RegistryKey registryKey = (key);
    if (registryKey != null)
    {
        result = ("").ToString();
    }
    ();

    return result;
}

/// <summary>
/// Decompress the compressed file in the format rar to the specified directory/// </summary>
/// <param name="rarFileName">Path to unzip the rar file</param>/// <param name="saveDir">Dir to save to after decompression</param>public static void DeCompressRar(string rarFileName, string saveDir)
{
    string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
    RegistryKey registryKey = (regKey);
    string winrarPath = ("").ToString();
    ();
    string winrarDir = (winrarPath);
    String commandOptions = ("x {0} {1} -y", rarFileName, saveDir);

    ProcessStartInfo processStartInfo = new ProcessStartInfo();
     = (winrarDir, "");
     = commandOptions;
     = ;

    Process process = new Process();
     = processStartInfo;
    ();
    ();
    ();
}

/// &lt;summary&gt;
/// Compress the directory and file into rar format and save it to the specified directory/// &lt;/summary&gt;
/// <param name="soruceDir">Folder Directory to be compressed</param>/// <param name="rarFileName">Compressed rar save path</param>public static void CompressRar(string soruceDir, string rarFileName)
{
    string regKey = @"SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\";
    RegistryKey registryKey = (regKey);
    string winrarPath = ("").ToString();
    ();
    string winrarDir = (winrarPath);
    String commandOptions = ("a {0} {1} -r", rarFileName, soruceDir);

    ProcessStartInfo processStartInfo = new ProcessStartInfo();
     = (winrarDir, "");
     = commandOptions;
     = ;
    Process process = new Process();
     = processStartInfo;
    ();
    ();
    ();
}

Compress and decompress zip files in C#.NET

Zip is a free and open source compression format. The Windows platform comes with zip compression and decompression tools. Since the algorithm is open source, there are many zip-based decompression open source libraries. SharpZipLib is a very good C# library. It can decompress files in zip, gzip and tar formats. First, download SharpZipLib and reference the assembly in your project. Below are some examples about SharpZipLib compression and decompression.

ZipOutputStream zipOutStream = new ZipOutputStream((""));
CreateFileZipEntry(zipOutStream, "", "");
CreateFileZipEntry(zipOutStream, @"folder1\folder2\folder3\", "");
();
("ZipOutPut");
 ZipInputStream zipInputStream = new ZipInputStream(("", ));
 ZipEntry zipEntryFromZippedFile = ();
 while (zipEntryFromZippedFile != null)
 {
     if ()
     {
         FileInfo fInfo = new FileInfo(("ZipOutPut\\{0}", ));
         if (!) ();

         FileStream file = ();
         byte[] bufferFromZip = new byte[];
         (bufferFromZip, 0, );
         (bufferFromZip, 0, );
         ();
     }
     zipEntryFromZippedFile = ();
 }
 ();

Unzip zip files using the class that comes with .NET

Microsoft has some classes about file decompression in namespace. If you just want to compress and decompress files in zip and gzip formats, it is a good choice. In the NET Framework 4.5 framework, a class called ZipFile has been added to the native assembly to make it easier to compress and decompress zip files. The examples of using ZipFile are as follows:

(@"e:\test", @"e:\test\"); //compression
(@"e:\test\", @"e:\test"); //Decompression

The most supported C# decompression open source library

While you are still struggling with the various compression formats above, a C# framework called SharpCompress is open source. You can find the open source code of the SharpCompress framework in search engines. It supports compression and decompression in rar 7zip, zip, tar, tzip and bzip2 formats. The following example reads and decompresses the file directly from the rar format file.

using (Stream stream = (@"C:\Code\"))
{
    var reader = (stream);
    while (())
    {
        if (!)
        {
            ();
            (@"C:\temp");
        }
    }
}

Summarize

Compared with rar and zip formats, rar has higher compression rate than zip and supports volume compression, but rar is a commercial software and requires payment. The zip compression rate is not as high as rar. However, open source is free, 7zip format is open source free, and the compression rate is relatively satisfactory. These compression formats have their own advantages. As for Microsoft platform and some open source platforms, the zip format is generally used because it is easier to implement through programming and is more reliable than rar.

/// &lt;summary&gt;
/// Decompress RAR and ZIP files (need to exist (as long as you can decompress or compress files on your computer, it will exist))/// &lt;/summary&gt;
/// <param name="UnPath">Decompressed file save directory</param>/// <param name="rarPathName">Absolute path (including file name) for decompression files (including file name)</param>/// <param name="IsCover">Will the unzipped file overwrite the existing file (if it is not overwritten, the unzipped file and the existing file with the same name will not exist together, and only the original existing file will be retained)</param>/// <param name="PassWord">Decompress password (empty if no password is needed)</param>/// <returns>true(decompression successfully); false(decompression failed)</returns>public static bool UnRarOrZip( string UnPath, string rarPathName, bool IsCover, string PassWord)
{
     if (!(UnPath))
         (UnPath);
     Process Process1 = new Process();
      = "" ;
      = true ;
     string cmd = "" ;
     if (! string .IsNullOrEmpty(PassWord) &amp;&amp; IsCover)
         //Decompress and encrypt the file and overwrite the existing file (-p password)         cmd = string .Format( " x -p{0} -o+ {1} {2} -y" , PassWord, rarPathName, UnPath);
     else if (! string .IsNullOrEmpty(PassWord) &amp;&amp; !IsCover)
         //Decompress and encrypt the file without overwriting the existing file (-p password)         cmd = string .Format( " x -p{0} -o- {1} {2} -y" , PassWord, rarPathName, UnPath);
     else if (IsCover)
         //Overwrite command (x -o+ means overwriting existing files)         cmd = string .Format( " x -o+ {0} {1} -y" , rarPathName,UnPath);
     else
         //Do not overwrite the command (x -o- means not overwriting existing files)         cmd = string .Format( " x -o- {0} {1} -y" , rarPathName, UnPath);
     //Order      = cmd;
     ();
     (); //Waiting for the process indefinitely     //==0 means normal execution, ==1 means abnormal execution     if ( == 0)
     {
         ();
         return true ;
     }
     else
     {
         ();
         return false ;
     }
 
}
 
/// &lt;summary&gt;
/// Compress the file into RAR or ZIP file (need to exist (as long as you can decompress or compress the file on your computer, it will exist))/// &lt;/summary&gt;
/// <param name="filesPath">Absolute path to the folder or file to be compressed</param>/// <param name="rarPathName">The compressed compressed file saves the absolute path (including file name)</param>/// <param name="IsCover">Will the compressed file overwrite the existing compressed file (if it is not overwritten, the compressed file and the existing compressed file of the same name will not exist together, and only the original existing compressed file will be retained)</param>/// <param name="PassWord">Compress password (empty if no password is needed)</param>/// <returns>true(compression successfully); false(compression failed)</returns>public static bool CondenseRarOrZip( string filesPath, string rarPathName, bool IsCover, string PassWord)
{
     string rarPath = (rarPathName);
     if (!(rarPath))
         (rarPath);
     Process Process1 = new Process();
      = "" ;
      = true ;
     string cmd = "" ;
     if (! string .IsNullOrEmpty(PassWord) &amp;&amp; IsCover)
         //Compress the encrypted file and overwrite the compressed file already exists (-p password -o+ overwrite)         cmd = string .Format( " a -ep1 -p{0} -o+ {1} {2} -r" , PassWord, rarPathName, filesPath);
     else if (! string .IsNullOrEmpty(PassWord) &amp;&amp; !IsCover)
         //Compress the encrypted file and do not overwrite the existing compressed file (-p password -o-not overwrite)         cmd = string .Format( " a -ep1 -p{0} -o- {1} {2} -r" , PassWord, rarPathName, filesPath);
     else if ( string .IsNullOrEmpty(PassWord) &amp;&amp; IsCover)
         //Compress and overwrite compressed files already exist (-o+overwrite)         cmd = string .Format( " a -ep1 -o+ {0} {1} -r" , rarPathName, filesPath);
     else
         //Compress and do not overwrite the existing compressed file (-o-not overwrite)         cmd = string .Format( " a -ep1 -o- {0} {1} -r" , rarPathName, filesPath);
     //Order      = cmd;
     ();
     (); //Waiting for the process indefinitely     //==0 means normal execution, ==1 means abnormal execution     if ( == 0)
     {
         ();
         return true ;
     }
     else
     {
         ();
         return false ;
     }
 
}

This is the article about C# compression or decompression rar and zip files. For more related C# compression and decompression rar and zip content, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!