2013-12-19 139 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