In this guide, we will cover the process of how to extract RAR files using C#. It has the resources to set the development environment, a list of steps that elaborates the programming logic, and a runnable sample code to unzip RAR files using C#. You will learn the options to extract the selected files only based on different criteria.
Steps to Unpack RAR Files using C#
- Set the environment to use Aspose.Zip for .NET to extract RAR files
- Load the source RAR file using the RarArchive class object
- Parse through all the entries in the RAR file
- Create a file stream using the entry name in each iteration
- Read all the bytes from the source entry and save them in the file stream
- Save each file on the disk after writing all the bytes
These steps elaborate on how to extract RAR using C#. The process is commenced by loading the source RAR file followed by parsing through all the entries in it. Create a separate file for each entry using its name and save all the bytes from the archive into the respective file before saving it on the disk.
Code to Extract RAR Files using C#
using System; | |
using System.IO; | |
using Aspose.Zip; | |
using Aspose.Zip.Rar; | |
class Program | |
{ | |
static void Main(string[] args) // Extract RAR | |
{ | |
// Set the license | |
new License().SetLicense("Aspose.Total.Product.Family.lic"); | |
// LLoad the RAR file | |
using (RarArchive rarArchive = new RarArchive("Sample.rar")) | |
{ | |
// Parse all the entries in the archive | |
foreach(var entry in rarArchive.Entries) | |
{ | |
// Create a file | |
var file = File.Create(entry.Name); | |
// Open the archive and save data to the file | |
using (var fileEntry = entry.Open()) | |
{ | |
byte[] data = new byte[1024]; | |
int bytesCount; | |
while ((bytesCount = fileEntry.Read(data, 0, data.Length)) > 0) | |
file.Write(data, 0, bytesCount); | |
// Close the file | |
file.Close(); | |
file.Dispose(); | |
} | |
} | |
} | |
Console.WriteLine("Done"); | |
} | |
} |
This article has taught us the process to unpack RAR using C#. If you want to unpack a ZIP file, refer to the article on how to extract ZIP file in C#.