ZetCode

C# TAR

last modified October 18, 2026

In this article we show how to work with TAR archives in C# using the System.Formats.Tar namespace.

TAR archive

A tar (tape archive) file is an archive of files. It is a common file format on Unix systems, used to package files together for backup or distribution. A TAR file is not compressed by itself; compression is added by a separate program or stream. A file with the .tar.gz or .tgz extension is a tar archive compressed with gzip.

.NET 7 and later contain the System.Formats.Tar namespace for reading and writing TAR files. It needs no extra NuGet package. Its main types are:

The examples run in a directory with the following layout. We have two text files and a subdirectory in the data directory.

$ find data -type f
data/words.txt
data/words2.txt
data/sub/note.txt

C# TarFile.CreateFromDirectory

The TarFile.CreateFromDirectory method creates a tar file that contains all the files and subdirectories from the specified directory.

Program.cs
using System.Formats.Tar;

try
{
    TarFile.CreateFromDirectory("data", "words.tar", includeBaseDirectory: false);
    Console.WriteLine($"created words.tar, {new FileInfo("words.tar").Length} bytes");
}
catch (IOException e)
{
    Console.WriteLine("failed to create archive");
    Console.WriteLine(e.Message);
}

The program creates a new tar archive from the files in the data directory.

TarFile.CreateFromDirectory("data", "words.tar", includeBaseDirectory: false);

The first parameter is the directory from which we take the files. The second is the archive name. The last parameter determines whether the base directory name is included as the first path segment in all the names of the archive entries. We pass false, so the entries are named words.txt instead of data/words.txt.

$ dotnet run
created words.tar, 8704 bytes

The tar format pads files to 512-byte blocks and the archive ends with empty blocks, so even a tiny archive is several kilobytes. We can check it with the standard tar tool.

$ tar tvf words.tar
-rw-rw-r-- jano/jano        21 2026-10-18 19:49 words2.txt
-rw-rw-r-- jano/jano        15 2026-10-18 19:49 words.txt
drwxrwxr-x jano/jano         0 2026-10-18 19:49 sub/
-rw-rw-r-- jano/jano         7 2026-10-18 19:49 sub/note.txt

C# TarFile.ExtractToDirectory

The TarFile.ExtractToDirectory method extracts the contents of a tar file into the specified directory.

Program.cs
using System.Formats.Tar;

Directory.CreateDirectory("out");

try
{
    TarFile.ExtractToDirectory("words.tar", "out", overwriteFiles: false);
    Console.WriteLine("archive extracted");
}
catch (IOException e)
{
    Console.WriteLine("failed to extract archive");
    Console.WriteLine(e.Message);
}

In the program, we extract the words.tar file into the out directory.

TarFile.ExtractToDirectory("words.tar", "out", overwriteFiles: false);

The third parameter controls what happens when a file already exists. With false, the method throws an IOException instead of overwriting it, which is why we catch that exception. Run the program twice to see the failure.

The method refuses to write outside the destination directory, so an archive with entries such as ../../etc/passwd cannot escape it. Even so, treat archives from untrusted sources with care and limit the extracted size.

$ dotnet run
archive extracted

C# TarReader

The TarReader reads a tar archive from a stream, one entry at a time. This is the way to list or inspect an archive without extracting it.

Program.cs
using System.Formats.Tar;

using FileStream fs = File.OpenRead("words.tar");
using var tr = new TarReader(fs);

TarEntry? entry;
while ((entry = tr.GetNextEntry()) is not null)
{
    Console.WriteLine($"{entry.EntryType,-16} {entry.Name,-16} {entry.Length,4}");
}

In the program, we list the entries of the archive.

using FileStream fs = File.OpenRead("words.tar");
using var tr = new TarReader(fs);

We open a file stream with File.OpenRead and create a TarReader from it.

TarEntry? entry;
while ((entry = tr.GetNextEntry()) is not null)
{
    Console.WriteLine($"{entry.EntryType,-16} {entry.Name,-16} {entry.Length,4}");
}

We go over the entries with GetNextEntry, which returns null at the end of the archive. The EntryType property distinguishes regular files, directories, symbolic links, and other kinds. The entries come in the order in which the directory was enumerated, which is not necessarily alphabetical.

$ dotnet run
RegularFile      words2.txt         21
RegularFile      words.txt          15
Directory        sub/                0
RegularFile      sub/note.txt        7

In the next example, we read the contents of the files in the archive.

Program.cs
using System.Formats.Tar;

using FileStream fs = File.OpenRead("words.tar");
using var tr = new TarReader(fs);

TarEntry? entry;
while ((entry = tr.GetNextEntry()) is not null)
{
    if (entry.EntryType != TarEntryType.RegularFile || entry.DataStream is null)
    {
        continue;
    }

    using var sr = new StreamReader(entry.DataStream);
    Console.WriteLine($"--- {entry.Name}");
    Console.Write(sr.ReadToEnd());
}

The program opens the tar file and prints the contents of the text files.

if (entry.EntryType != TarEntryType.RegularFile || entry.DataStream is null)
{
    continue;
}

Only regular files have data. The DataStream property is null for directories and entries without content.

using var sr = new StreamReader(entry.DataStream);
Console.Write(sr.ReadToEnd());

The data stream is a regular Stream, so we wrap it in a StreamReader and read the text directly, without copying it to a memory stream first. When the archive stream is not seekable, the data stream is only valid until the next call to GetNextEntry, unless we ask the reader to copy the data with GetNextEntry(copyData: true).

$ dotnet run
--- words2.txt
sky
the stormy night
--- words.txt
old falcon
owl
--- sub/note.txt
nested

C# TarWriter

The TarWriter creates an archive entry by entry. We can add files from disk, data from memory, and directories.

Program.cs
using System.Formats.Tar;
using System.Text;

using (FileStream fs = File.Create("custom.tar"))
using (var tw = new TarWriter(fs))
{
    // from a file on disk
    tw.WriteEntry("data/words.txt", "words.txt");

    // from memory
    var bytes = Encoding.UTF8.GetBytes("created in memory\n");
    var entry = new PaxTarEntry(TarEntryType.RegularFile, "memory.txt")
    {
        DataStream = new MemoryStream(bytes)
    };
    tw.WriteEntry(entry);

    // a directory entry
    tw.WriteEntry(new PaxTarEntry(TarEntryType.Directory, "docs/"));
}

using FileStream rs = File.OpenRead("custom.tar");
using var tr = new TarReader(rs);

while (tr.GetNextEntry() is { } e)
{
    Console.WriteLine($"{e.EntryType,-12} {e.Name}");
}

The program writes three entries and then reads them back.

tw.WriteEntry("data/words.txt", "words.txt");

This overload reads a file from the disk. The first argument is the path of the file, the second is the name of the entry in the archive.

var entry = new PaxTarEntry(TarEntryType.RegularFile, "memory.txt")
{
    DataStream = new MemoryStream(bytes)
};
tw.WriteEntry(entry);

To write data that is not in a file, we create an entry object and assign a DataStream. PaxTarEntry is the default format of the writer; it supports long names and extended attributes.

tw.WriteEntry(new PaxTarEntry(TarEntryType.Directory, "docs/"));

A directory entry has no data stream. The disposal of the writer at the end of the using block writes the closing blocks of the archive, so we must dispose it before reading the file.

$ dotnet run
RegularFile  words.txt
RegularFile  memory.txt
Directory    docs/

C# TAR with gzip compression

The .NET tar API works on streams, so we can combine it with GZipStream to produce and consume .tar.gz files. The TarFile class also has asynchronous variants of its methods.

Program.cs
using System.Formats.Tar;
using System.IO.Compression;

// create words.tar.gz
using (FileStream fs = File.Create("words.tar.gz"))
using (var gz = new GZipStream(fs, CompressionLevel.Optimal))
{
    await TarFile.CreateFromDirectoryAsync("data", gz, includeBaseDirectory: false);
}

Console.WriteLine($"tar:    {new FileInfo("words.tar").Length} bytes");
Console.WriteLine($"tar.gz: {new FileInfo("words.tar.gz").Length} bytes");

// extract it
Directory.CreateDirectory("out-gz");
using (FileStream fs = File.OpenRead("words.tar.gz"))
using (var gz = new GZipStream(fs, CompressionMode.Decompress))
{
    await TarFile.ExtractToDirectoryAsync(gz, "out-gz", overwriteFiles: true);
}

Console.WriteLine(string.Join(", ", Directory.GetFiles("out-gz", "*", SearchOption.AllDirectories).Order()));

The program creates a gzip-compressed archive, compares the sizes, and extracts the archive again.

using (FileStream fs = File.Create("words.tar.gz"))
using (var gz = new GZipStream(fs, CompressionLevel.Optimal))
{
    await TarFile.CreateFromDirectoryAsync("data", gz, includeBaseDirectory: false);
}

We pass the compression stream, instead of a file name, as the destination. The gzip stream is disposed at the end of the block, which finishes the compressed data.

using var gz = new GZipStream(fs, CompressionMode.Decompress)
await TarFile.ExtractToDirectoryAsync(gz, "out-gz", overwriteFiles: true);

For extraction, we wrap the input file in a decompressing GZipStream and give it to ExtractToDirectoryAsync.

$ dotnet run
tar:    8704 bytes
tar.gz: 346 bytes
out-gz/sub/note.txt, out-gz/words.txt, out-gz/words2.txt

The compressed archive is much smaller, because the tar padding is mostly zero bytes. The result is compatible with tar xzf words.tar.gz.

Source

TarFile class

In this article we have worked with tar files in C#.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all C# tutorials.