There is a neat little trick that one has to follow inorder to zip a entire folder into a gzip file.
It is essentially a two step process
- Zip individual files in a folder using TarArchive
- Zip the tar file using GZip
1: public static string CreateTar(string directoryToCompress, string destPath, string tarFile)
2: {
3: string destDrive = destPath.Substring(0, destPath.IndexOf(@"\") + 1);
4: Directory.SetCurrentDirectory(destDrive);
5: string tarFilePath = Path.Combine(destPath, tarFile);
6: using (Stream fs = new FileStream(tarFilePath, FileMode.OpenOrCreate))
7: {
8: using (TarArchive ta = TarArchive.CreateOutputTarArchive(fs))
9: {
10: string[] files = Directory.GetFiles(directoryToCompress);
11: foreach (string file in files)
12: {
13: string entry = file.Substring(file.IndexOf(@"\") + 1);
14: TarEntry te = TarEntry.CreateEntryFromFile(entry);
15: ta.WriteEntry(te, false);
16: }
17: }
18: }
19: return tarFilePath;
20: }
The above code creates the tar File. Note to create the Tar using TarArchive I used ICSharpCode.SharpZipLib.dll
The following code Zips the Tar file into a Gzip file:
1: public static void CreateTarGzip()
2: {
3: string sourceFolder = @"C:\beehive\stagingwebevent\20090324_00\";
4: string file = CreateTar(sourceFolder, @"C:\core\", "test.tar");
5: string outputFile = @"C:\core\test.tgz";
6: using (FileStream fs = new FileStream(outputFile, FileMode.CreateNew))
7: using (GZipStream s = new GZipStream(fs, CompressionMode.Compress))
8: {
9: using (FileStream inputfs = new FileStream(file, FileMode.Open))
10: {
11: byte[] buffer = new byte[4096];
12: int len = 0;
13: while ((len = inputfs.Read(buffer, 0, buffer.Length)) > 0)
14: {
15: s.Write(buffer, 0, len);
16: }
17: }
18: }
19: }