SharpZipLib - adding folders/directories to a zip

2019-07-15 02:48发布

问题:

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?

回答1:

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