[英]How to validate that a file is a password protected ZIP file, using C#
给定文件的路径,如何验证该文件是受密码保护的zip文件?
即,我该如何实现这个功能?
bool IsPasswordProtectedZipFile(string pathToFile)
我不需要解压缩文件 - 我只需要验证它是ZIP并且已经受到一些密码的保护。
谢谢
使用SharpZipLib ,以下代码可以正常工作。 并且通过工作我的意思是entry.IsCrypted
根据zip文件中的第一个条目是否有密码返回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;
}
}
请注意,没有真正的错误处理或任何事情......
在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;
}
}
在.NET Framework成熟度的这一点上,您将需要使用第三方工具。 有很多商业图书馆可以用Google搜索。 我建议微软的Codeplex网站DotNetZip免费提供一个。 首页说明“ 库支持zip密码 ”。
没有100%正确的方法来检查所有zip条目是否已加密。 zipfile中的每个条目都是独立的,可以有自己的密码/加密方法。
对于大多数情况,zipfile是由某些软件压缩的,这些软件将确保zipfile中的每个条目都有一个通用密码和加密方法。
因此,使用第一个zipentry(不是目录)来检查该zipfile是否已加密可以涵盖大多数情况。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.