zip目录与专用的子文件夹

时间:2013-12-19 10:23:10

标签: c# dotnetzip

我正在尝试将文件夹目录打包到zip目录中,不包括所有子文件夹。

目前我正在使用此方法打包整个目录。

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
   }
}

这项工作真的很棒,但现在我有一个

 List<string> paths 

在我希望在zipArchive中拥有的子文件夹的路径中。其他子文件夹(不在列表中)不应该在存档中

谢谢

1 个答案:

答案 0 :(得分:3)

我无法找到任何非递归添加文件夹的内置函数。所以我写了一个手动添加它们的函数:

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));
    }
}

我没有测试过,你能告诉我这是否对你有用吗?