How to create tar.gz file in C#

Stavros picture Stavros · Aug 5, 2015 · Viewed 13.5k times · Source


I have tried SevenZipLib and SevenZipSharp, but without success. Can someone give me a working example of archiving a text file to tar.gz, using any free library?
I know it's not the best way to go for zipping, but it's a requirement I have.

Answer

Panagiotis Kanavos picture Panagiotis Kanavos · Aug 5, 2015

Perhaps the most popular package in NuGet that supports TAR is SharpZipLib. Its wiki includes examples for working with tar.gz files, including creation. The linked example archives an entire folder.

To archive a single file, the sample can be simplified to this:

private void CreateTarGZ(string tgzFilename, string fileName)
{
    using (var outStream = File.Create(tgzFilename))
    using (var gzoStream = new GZipOutputStream(outStream))
    using (var tarArchive = TarArchive.CreateOutputTarArchive(gzoStream))
    {
        tarArchive.RootPath = Path.GetDirectoryName(fileName);

        var tarEntry = TarEntry.CreateEntryFromFile(fileName);
        tarEntry.Name = Path.GetFileName(fileName);

        tarArchive.WriteEntry(tarEntry,true);
    }
}

Essentially, you need to create a TarEntry for each folder and file you want to store.