SharpZipLib - adding folders/directories to a zip archive

MoSlo picture MoSlo · Jun 15, 2011 · Viewed 9.5k times · Source

From examples, I've got a pretty good grasp over how to extract a zip file.

In nearly every example, the method of identifying when a ZipEntry is a directory is as follows

string directoryName = Path.GetDirectoryName(theEntry.Name);
string fileName = Path.GetFileName(theEntry.Name);

if (directoryName.Length > 0)
  Directory.CreateDirectory(Path.Combine(destinationDirectory, directoryName));                    

if (fileName != String.Empty)
{
  //read data and write to file
}

Now is is fine and all (directory encountered, create it), directory is available when the file is extracted.

I can add files to a zip fine, but how do I add folders? I understand I'll be looping through the directories, adding the files encountered (and their ZipEntry.Name property is populated properly), but how do I add a ZipEntry to the archive and instruct the ZipOutputStream that it is a directory?

Answer

Steve Townsend picture Steve Townsend · Jun 15, 2011

ZipFile.AddDirectory does what you want. Small sample code here.