Extracting RAR Archives in .NET
Overview
Aspose.ZIP API lets extract archives in your applications without the need of any other 3rd party applications. Aspose.ZIP API provides RarArchive class to work with RAR archives. API provides the RarArchiveEntryclass to represents a single file within the RAR archive.
Creation of RAR archives is not possible.
Extract an Entry
The following code example demonstrates how to extract an entry using RarArchive instance.
Steps: Extract an Entry from a RAR Archive via C#
- Open the RAR archive using the RarArchive instance.
- Create a new file stream for the extracted entry.
- Use the Open method on the first entry to retrieve its content.
- Use a buffer to read the data from the entry and write it to the destination file stream until all bytes are transferred.
1 using (RarArchive archive = new RarArchive("archive.rar"))
2 {
3 using (var destination = File.Create(dataDir + "firstEntry.txt"))
4 {
5 using (var source = archive.Entries[0].Open())
6 {
7 byte[] buffer = new byte[1024];
8 int bytesRead;
9 while ((bytesRead = source.Read(buffer, 0, buffer.Length)) > 0)
10 destination.Write(buffer, 0, bytesRead);
11
12 }
13 }
14 }
Extract an Encrypted Entry
The following code example demonstrates how to extract an encrypted entry using RarArchive instance.
Steps: Extract an Encrypted Entry from a RAR Archive via C#
- pen the encrypted RAR archive using a FileInfo object.
- Create a file stream for the extracted entry.
- Use the Extract method on the first entry, providing the password required to decrypt it.
- Write the decrypted data to the destination file.
1 FileInfo fi = new FileInfo("encrypted.rar");
2 using (RarArchive archive = new RarArchive(fi.OpenRead()))
3 {
4 using (var destination = File.Create(dataDir + "firstEntry.txt"))
5 {
6 archive.Entries[0].Extract(destination, "p@s$w0rd");
7 }
8 }
Extracting Compressed Directory
The following code example demonstrates how to all the files from RarArchive instance.
Steps: Extract All Files from a Compressed Directory (RAR Archive) via C#
- Open the RAR archive using the RarArchive instance.
- Use the ExtractToDirectory method to extract all files from the archive to the specified directory.
1 using (RarArchive archive = new RarArchive("archive.rar"))
2 {
3 archive.ExtractToDirectory("extracted");
4 }