2013-12-19 140 views
2

我试图将文件夹目录打包到一个zip目录,不包括所有的子文件夹。专用子文件夹的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的childfolders内

。其他childfolders(不在列表中)不应该在归档

谢谢

+0

为什么不简单地在你的路径上创建一个foreach循环并为每个路径调用'directoryPacker()'? – RononDex

+0

,因为我在directoryPacker()中做了其他的事情,并且不需要这个子文件夹...只对于根目录 – patdhlk

+0

你是否有单独的子文件夹和rootfolders函数呢? – RononDex

回答

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

我没有测试它,你能告诉我,如果这对你的作品?

+0

谢谢..我会在几分钟内测试 – patdhlk

+0

它的工作真的很棒,谢谢:D – patdhlk