Search code examples
c#dotnetzip

zip directory with dedicate childfolders


I'm trying to pack a folder directory into a zip directory, not including all child folders.

currently i m using this method to pack the whole directory.

public void directoryPacker(DirectoryInfo directoryInfo)
{
   string pathToRootDirectory = Path.Combine(directoryInfo.Parent.FullName,
                               directoryInfo.Name) + ".abc"; //name of root file
   using(ZipContainer zip = new ZipContainer(pass)) 
   //ZipContainer inherits from Ionic.Zip.ZipFile
   {
       //some password stuff here
       //
       //zipping
       zip.AddDirectory(directoryInfo.FullName, "/"); //add complete subdirectory to *.abc archive (zip archive)
       File.Delete(pathToRootDirectory);
       zip.Save(pathToRootDirecotry); //save in rootname.bdd
   }
}

this works really great, but now i have a

 List<string> paths 

within the paths to the childfolders which i want to have in my zipArchive. The other childfolders(not in the list) should not be in the archive

thank you


Solution

  • I couldn't find any built in function that adds folder non-recursively. So I wrote a function that adds them manually:

    public void directoryPacker(DirectoryInfo directoryInfo)
    {
        // The list of all subdirectory relatively to the rootDirectory, that should get zipped too
        var subPathsToInclude = new List<string>() { "subdir1", "subdir2", @"subdir2\subsubdir" };
    
        string pathToRootDirectory = Path.Combine(directoryInfo.Parent.FullName,
                                    directoryInfo.Name) + ".abc"; //name of root file
        using (ZipContainer zip = new ZipContainer(pass))
        //ZipContainer inherits from Ionic.Zip.ZipFile
        {
            // Add contents of root directory
            addDirectoryContentToZip(zip, "/", directoryInfo.FullName);
    
            // Add all subdirectories that are inside the list "subPathsToInclude"
            foreach (var subPathToInclude in subPathsToInclude)
            {
                var directoryPath = Path.Combine(new[] { directoryInfo.FullName, subPathToInclude });
                if (Directory.Exists(directoryPath))
                {
                    addDirectoryContentToZip(zip, subPathToInclude.Replace("\\", "/"), directoryPath);
                }
            }
    
    
            if (File.Exists(pathToRootDirectory))
                File.Delete(pathToRootDirectory);
    
            zip.Save(pathToRootDirecotry); //save in rootname.bdd
        }
    }
    
    private void addDirectoryContentToZip(ZipContainer zip, string zipPath, DirectoryInfo directoryPath)
    {
        zip.AddDirectoryByName(zipPath);
        foreach (var file in directoryPath.GetFiles())
        {
            zip.AddFile(file, zipPath + "/" + Path.GetFileName(file.FullName));
        }
    }
    

    I did not test it, can you tell me if this works for you?