prosseek
prosseek

Reputation: 191109

Gzip a directory that has subdirectories using GZipStream class with C#?

This MSDN site has an example to gzip a file. Then, how can I gzip a whole directory with sub directories in it?

Upvotes: 2

Views: 3292

Answers (4)

amr ras
amr ras

Reputation: 302

You can zip the directory in pure .NET 3.0. Using SharpZipLib may not be desirable due to the modified GPL license.

First, you will need a reference to WindowsBase.dll.

This code will open or create a zip file, create a directory inside, and place the file in that directory. If you want to zip a folder, possibly containing sub-directories, you could loop through the files in the directory and call this method for each file. Then, you could depth-first search the sub-directories for files, call the method for each of those and pass in the path to create that hierarchy within the zip file.

public void AddFileToZip(string zipFilename, string fileToAdd, string destDir)
{
    using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
    {
        string destFilename = "." + destDir + "\\" + Path.GetFileName(fileToAdd);
        Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
        if (zip.PartExists(uri))
        {
            zip.DeletePart(uri);
        }
        PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);

        using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
        {
            using (Stream dest = part.GetStream())
            {
                CopyStream(fileStream, dest);
            }
        }
    }
}

destDir could be an empty string, which would place the file directly in the zip.

Sources: https://weblogs.asp.net/jongalloway/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib

https://weblogs.asp.net/albertpascual/creating-a-folder-inside-the-zip-file-with-system-io-packaging

Upvotes: 0

joce
joce

Reputation: 9902

Since gzip only works on files, I suggest you tar your directory and then gzip the generated tar file.

You can use tar-cs or SharpZipLib to generate your tar file.

Upvotes: 2

Sam Axe
Sam Axe

Reputation: 33738

gzip operates on a simgle stream. To create a multi-stream (multi-file) archive using the gzipstream you need to include your own index. Basicly, at its simplest you would write the file offsets to the beginning of the output stream and then when you read it back in you know where the boundaries are. This method would not be PKZIP compatible. To be compatible you would have to read and implement the ZIP format... or use something like SharpZip, or Zip.NET

Upvotes: 0

Arnaud F.
Arnaud F.

Reputation: 8462

You can't !

GZip was created for file, not directories :)

Upvotes: 0

Related Questions