2012-09-23 48 views
5

我正在使用dotnetzip庫創建zip文件。如何使用dotnetzip檢查文件是否存在於zip文件中

但我不知道如何檢查壓縮文件是否存在。如果文件存在,那麼我將用路徑更新文件。

public void makezip(string flname) 
    { 
     string fln =flname; 
     string curFile = @"d:\crs.zip"; 
     if (File.Exists(curFile)) 
     { 
       ZipFile zipfl = ZipFile.Read(@"D:\crs.zip"); 
      var result = zipfl.Any(entry => entry.FileName.EndsWith(@fln)); 
      if (result == true) { 
       zipfl.UpdateFile(@fln); 
       }else{ 
        zipfl.AddFile(@fln); 
       } 
      zipfl.Save(@"d:\crs.zip"); 
     } 
     else 
     { 
      try 
      { 
       ZipFile zipfl = new ZipFile(); 

       var result = zipfl.Any(entry => entry.FileName.EndsWith(@fln)); 
       if (result == true) 
       { 
        zipfl.AddFile(@fln); 
       } 
       zipfl.Save(@"d:\crs.zip"); 
      }catch { 
       MessageBox.Show("Invalid Zip File"); 

      }}} 
+0

代碼,我嘗試做 – chetan

+0

哪個具體的例子,它是怎麼回事? –

+0

我正在通過一個循環調用這個函數。並將路徑傳遞給文件名。我得到錯誤「一個項目與相同的密鑰已被添加」 – chetan

回答

8

如何檢查文件是否在zip文件存在?

只要使用LINQ Any,假設你有輸入zip文件input.zip,檢查input.zip是否包含input.txt:(這不是dotnetzip,但會完成這項工作)

var zipFile = ZipFile.Read(@"C:\input.zip"); 
var result = zipFile.Any(entry => entry.FileName.EndsWith("input.txt")); 
+1

+1;但有一點要注意:如果我沒有弄錯,FileEntry.FileName也可能包含(部分)目錄路徑,請參見[here](http://dotnetzip.herobo.com/DNZHelp/html/913abfd3 -bbc6-803c-858B-f53dfb008e55.htm)。 –

+0

@AndersGustafsson:謝謝,我已經運行這段代碼,它不containe目錄路徑 –

+0

我如何檢查是否文件有像C文件夾的信息:\ AB \ input.txt中 – chetan

2

要求:using System.IO.Compression;

程序集:System.IO.Compression.FileSystem.dll

public static bool ZipHasFile(string fileFullName, string zipFullPath) 
{ 
    using (ZipArchive archive = ZipFile.OpenRead(zipFullPath)) //safer than accepted answer 
    { 
     foreach (ZipArchiveEntry entry in archive.Entries) 
     { 
      if (entry.FullName.EndsWith(fileFullName, StringComparison.OrdinalIgnoreCase)) 
      { 
       return true; 
      } 
     } 
    } 
    return false; 
} 

調用示例:添加var exists = ZipHelper.ZipHasFile(@"zipTest.txt", @"C:\Users\...\Desktop\zipTest.zip");

+0

請注意使用Mac壓縮的解壓縮文件。這些.zip可能包含一個子目錄「_MACOSX」。我首先通過測試Contains(「_ MACOSX」)並繼續進行忽略。 –

相關問題