Given a path to a file, how can I validate that the file is a password-protected zip file?
i.e., how would I implement this function?
bool IsPasswordProtectedZipFile(string pathToFile)
I don't need to unzip the file -- I just need to verify that it's a ZIP and has been protected with some password.
Thanks
Using SharpZipLib, the following code works. And by works I mean
entry.IsCrypted
returns true or false based on whether or not there is a password for the first entry in the zip file.There's a simple tutorial on using SharpZipLib on CodeProject.
Thus a simple implementation looks something like:
Note there's no real error handling or anything...
At this point in the .NET Framework maturity you will need to use a 3rd party tool. There are many commercial libraries that can be Googled. I'm suggesting one free one from Microsoft's Codeplex website DotNetZip. The front page states "the library supports zip passwords".
In ZIP archives, the password is not placed on the file, but on the individual entries within the file. A zip can contain some entries encrypted and some not. Here's some example code to check for encryption on entries in DotNetZip:
If you'd prefer, you can use LINQ:
There is no 100% correct way to check if all zip entries is encrypted. every entry in a zipfile is independent and could has its own password/encrypted method.
for most cases, zipfile is zipped by some software, these software will ensure every entry in a zipfile has a common password and encrypted method.
So, using the first zipentry(not a directory) to check if that zipfile is encrypted can cover most cases.