2009-10-28 27 views
3

給定一個文件路徑,如何驗證該文件是受密碼保護的zip文件?如何使用C#驗證文件是否爲受密碼保護的ZIP文件

即,我將如何實現此功能?

bool IsPasswordProtectedZipFile(string pathToFile) 

我不需要解壓縮文件 - 我只需要驗證它是一個ZIP,並已用一些密碼保護。

謝謝

+0

看到這個問題:[如何在c#程序中使用密碼進行壓縮和解壓縮](http://stackoverflow.com/questions/1607858/how-to-zip-and-unzip-using-password-in-c-程序) – manji 2009-10-28 21:38:54

回答

3

使用SharpZipLib,以下代碼工作。根據作品,我的意思是entry.IsCrypted根據壓縮文件中第一個條目是否存在密碼來返回true或false。

var file = @"c:\testfile.zip"; 
FileStream fileStreamIn = new FileStream(file, FileMode.Open, FileAccess.Read); 
ZipInputStream zipInStream = new ZipInputStream(fileStreamIn); 
ZipEntry entry = zipInStream.GetNextEntry(); 
Console.WriteLine("IsCrypted: " + entry.IsCrypted); 

有上CodeProject使用SharpZipLib一個簡單的教程。

這樣一個簡單的實現看起來是這樣的:

public static bool IsPasswordProtectedZipFile(string path) 
{ 
    using (FileStream fileStreamIn = new FileStream(path, FileMode.Open, FileAccess.Read)) 
    using (ZipInputStream zipInStream = new ZipInputStream(fileStreamIn)) 
    { 
     ZipEntry entry = zipInStream.GetNextEntry(); 
     return entry.IsCrypted; 
    } 
} 

注意有沒有真正的錯誤處理或什麼...

+0

謝謝 - 我現在意識到的關鍵點是我需要查看ZIP中的單個條目,因爲它們可以單獨加密。密碼不適用於整個ZIP文件。 Codeplex的DotNetZip也具有類似的功能。 – frankadelic 2009-10-29 05:39:42

+0

是的,確切地說。因此,例如,您可能想要掃描整個存檔,查找具有密碼的_any_條目,而不僅僅是第一個... – 2009-10-29 08:15:25

1

在.NET Framework成熟度的這一點上,您將需要使用第三方工具。有許多商業圖書館可以谷歌搜索。我建議從微軟的Codeplex網站DotNetZip免費提供一個。首頁陳述「該庫支持郵編密碼」。

3

在ZIP檔案,密碼不放在文件,但在文件中的單個條目。一個zip可以包含一些條目加密,有些則不是。下面是一些示例代碼中DotNetZip檢查加密的條目:

int encryptedEntries = 0; 
using (var zip = ZipFile.Read(nameOfZipFile)) 
{ 
    // check a specific, named entry: 
    if (zip["nameOfEntry.doc"].UsesEncryption) 
     Console.WriteLine("Entry 'nameOfEntry.doc' uses encryption"); 

    // check all entries: 
    foreach (var e in zip) 
    { 
     if (e.UsesEncryption) 
     { 
      Console.WriteLine("Entry {0} uses encryption", e.FileName); 
      encryptedEntries++; 
     } 
    } 
} 

if (encryptedEntries > 0) 
    Console.WriteLine("That zip file uses encryption on {0} entrie(s)", encryptedEntries); 

如果你願意,你可以使用LINQ:

private bool ZipUsesEncryption(string archiveToRead) 
{ 
    using (var zip = ZipFile.Read(archiveToRead)) 
    { 
     var selection = from e in zip.Entries 
      where e.UsesEncryption 
      select e; 

     return selection.Count > 0; 
    } 
} 
+0

謝謝。我也發現了這個DotNetZip解決方案 - 請參閱上面接受的答案中的我的評論。 – frankadelic 2009-10-29 16:24:50

0

還有就是要檢查是否所有的拉鍊沒有100%的正確方法條目被加密。 zipfile中的每個條目都是獨立的,並且可以擁有自己的密碼/加密方法。

對於大多數情況下,zipfile被一些軟件壓縮,這些軟件將確保zipfile中的每個條目都有一個公用密碼和加密方法。

因此,使用第一個zipentry(不是目錄)來檢查該zip文件是否被加密可以覆蓋大多數情況。

相關問題