Working with TAR Archives
Overview
A Tar archive lets you combine multiple files into a single container while preserving names, timestamps, and directory structure. Aspose.ZIP for .NET can both compose and extract TAR archives, and it can work with common TAR variants such as v7, GNU, and POSIX/PAX headers.
Collecting without compression
The following example demonstrates how to gather two files into a TAR archive:
1 using (FileStream tarFile = File.Open("joint.tar", FileMode.Create))
2 {
3 FileInfo fi1 = new FileInfo("text.txt");
4 FileInfo fi2 = new FileInfo("picture.png");
5
6 using (var archive = new TarArchive())
7 {
8 archive.CreateEntry("text.txt", fi1);
9 archive.CreateEntry("picture.png", fi2);
10 archive.Save(tarFile);
11 }
12 }Compressing tar archive
On Unix-like operating systems, the tar utility can automatically compress a
tar archive with gzip during creation. Aspose.Zip provides similar functionality using the
SaveGzipped method.
1 using (var archive = new TarArchive())
2 {
3 archive.CreateEntry("text.txt", @"D:\texts\article.txt");
4 archive.CreateEntry("picture.png", @"D:\Picture\photo.png");
5 archive.SaveGzipped("result.tar.gz");
6 }The xz utility is increasingly popular on Linux and Unix systems. Its TAR compression can be easily performed using the SaveXzCompressed method of a tar archive.
1 using (FileStream xzFile = File.Open("archive.tar.xz", FileMode.Create))
2 {
3 using (var archive = new TarArchive())
4 {
5 archive.CreateEntry("text.txt", @"D:\texts\article.txt");
6 archive.CreateEntry("picture.png", @"D:\Picture\photo.png");
7 archive.SaveXzCompressed(xzFile);
8 }
9 }Just like gzip and xz compression, Aspose.Zip lets you easily combine TAR archiving with Lzip, Zstandard, LZ4, or LZMA compression.
Extract whole TAR archive
To unpack the complete contents of a TAR archive, call ExtractToDirectory:
1 using (TarArchive archive = new TarArchive("archive.tar"))
2 {
3 archive.ExtractToDirectory("extracted");
4 }Extract a selected TAR entry
If you only need one file from the archive, extract that entry directly to a file path or stream:
1 using (TarArchive archive = new TarArchive("archive.tar"))
2 {
3 TarEntry entry = archive.Entries.First();
4
5 using (MemoryStream output = new MemoryStream())
6 {
7 entry.Extract(output);
8 }
9 }This is useful when you want to inspect a file in memory or pull only a specific payload from a large TAR archive without unpacking the entire directory tree.