Skip to content

Instantly share code, notes, and snippets.

@lawrencekgrant
Created July 10, 2011 02:14
Show Gist options
  • Save lawrencekgrant/1074168 to your computer and use it in GitHub Desktop.
Save lawrencekgrant/1074168 to your computer and use it in GitHub Desktop.
Compress to tar.gz
private void CreateTarGZ (string tgzFilename, string sourceDirectory)
{
Stream outStream = File.Create (tgzFilename);
Stream gzoStream = new GZipOutputStream (outStream);
TarArchive tarArchive = TarArchive.CreateOutputTarArchive (gzoStream);
// Note that the RootPath is currently case sensitive and must be forward slashes e.g. "c:/temp"
// and must not end with a slash, otherwise cuts off first char of filename
// This is scheduled for fix in next release
tarArchive.RootPath = sourceDirectory.Replace ('\\', '/');
if (tarArchive.RootPath.EndsWith ("/"))
tarArchive.RootPath = tarArchive.RootPath.Remove (tarArchive.RootPath.Length - 1);
AddDirectoryFilesToTar (tarArchive, sourceDirectory, true);
tarArchive.Close ();
}
private void AddDirectoryFilesToTar (TarArchive tarArchive, string sourceDirectory, bool recurse)
{
// Optionally, write an entry for the directory itself.
// Specify false for recursion here if we will add the directory's files individually.
//
TarEntry tarEntry = TarEntry.CreateEntryFromFile (sourceDirectory);
tarArchive.WriteEntry (tarEntry, false);
// Write each file to the tar.
//
string[] filenames = Directory.GetFiles (sourceDirectory);
foreach (string filename in filenames) {
tarEntry = TarEntry.CreateEntryFromFile (filename);
tarArchive.WriteEntry (tarEntry, true);
}
if (recurse) {
string[] directories = Directory.GetDirectories (sourceDirectory);
foreach (string directory in directories)
AddDirectoryFilesToTar (tarArchive, directory, recurse);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment