我保存的PowerPoint演示文稿爲.ppt,並有和沒有打開它們需要密碼文稿.pptx,在7-Zip的睜開眼睛,並來到了初步結論,即
- .pptx格式無需密碼始終使用標準的.zip文件格式
- .PPT文件CompoundDocuments
- 用密碼.pptx格式也CompoundDocuments
- 所有需要密碼CompoundDocuments包含名爲*加密*
條目
要運行這段代碼,您需要安裝NuGet包OpenMcdf。這是我可以找到的用於閱讀CompoundDocuments的第一個C#庫。
using OpenMcdf;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace _22916194
{
//http://stackoverflow.com/questions/22916194/detecing-password-protected-ppt-and-xls-documents
class Program
{
static void Main(string[] args)
{
foreach (var file in args.Where(File.Exists))
{
switch (Path.GetExtension(file))
{
case ".ppt":
case ".pptx":
Console.WriteLine($"* {file} " + (HasPassword(file) ? "is " : "isn't ") + "passworded");
Console.WriteLine();
break;
default:
Console.WriteLine($" * Unknown file type: {file}");
break;
}
}
Console.ReadLine();
}
private static bool HasPassword(string file)
{
try
{
using (var compoundFile = new CompoundFile(file))
{
var entryNames = new List<string>();
compoundFile.RootStorage.VisitEntries(e => entryNames.Add(e.Name), false);
//As far as I can see, only passworded files contain an entry with a name containing Encrypt
foreach (var entryName in entryNames)
{
if (entryName.Contains("Encrypt"))
return true;
}
compoundFile.Close();
}
}
catch (CFFileFormatException) {
//This is probably a .zip file (=unprotected .pptx)
return false;
}
return false;
}
}
}
你應該能夠擴展該代碼來處理其他的Office格式。頂部的結論應該是真實的,除了您需要在CompoundDocument中查找一些其他數據而不是包含* Encrypt *的文件名(我快速查看了.doc文件並且它看起來沒有完全相同)。
你是如何管理的? – TechnicalSmile
我試圖挖掘我的舊代碼,但我想我只是沒有弄明白,最終放棄了。對不起:( – silent
爲xls(x)文件,使用npoi可能是一個選項?看到這裏:http://stackoverflow.com/questions/28604371/how-to-check-if-xlsx-file-is-password-protected -or-not-using-apache-poi -npoi是apache poi的c#端口,在我的其中一個項目中使用它,它可以很好地與xls和xlsx-files一起檢查密碼,但不知道它們是如何做到的。可能更多的是挖掘他們如何做到這一點:https://svn.apache.org/repos/asf/poi/trunk/ – Dominik