我正在开发一个网站,该网站允许用户上传不同的文件格式。我们需要限制用户上传受密码保护的文件。
有没有办法在上传文件之前确定 Microsoft Office 文件(Word、Powerpoint 和 Excel)是否受密码保护?根据http://social.msdn.microsoft.com/Forums/en/oxmlsdk/thread/34701a34-f1d4-4802-9ce4-133f15039c69,我已经实现了以下内容,但它抛出一个错误,提示“文件包含损坏的数据” ,同时尝试打开受密码保护的文件。
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(mem, false))
{
DocumentProtection dp =
wordDoc.MainDocumentPart.DocumentSettingsPart.Settings.GetFirstChild<DocumentProtection>();
if (dp != null && dp.Enforcement == DocumentFormat.OpenXml.OnOffValue.FromBoolean(true))
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
还有其他方法可以确定这一点吗?
尝试一下这段代码:
\n\npublic static Boolean IsProtected(String file)\n{\n Byte[] bytes = File.ReadAllBytes(file);\n\n String prefix = Encoding.Default.GetString(bytes.Take(2).ToArray());\n\n // Zip and not password protected.\n if (prefix == "PK")\n return false;\n\n // Office format.\n if (prefix == "\xc3\x90\xc3\x8f")\n {\n // XLS 2003\n if (bytes.Skip(0x208).Take(1).ToArray()[0] == 0xFE)\n return true;\n\n // XLS 2005\n if (bytes.Skip(0x214).Take(1).ToArray()[0] == 0x2F)\n return true;\n\n // DOC 2005\n if (bytes.Skip(0x20B).Take(1).ToArray()[0] == 0x13)\n return true;\n\n // Guessing\n if (bytes.Length < 2000)\n return false;\n\n // DOC/XLS 2007+\n String start = Encoding.Default.GetString(bytes.Take(2000).ToArray()).Replace("\\0", " ");\n\n if (start.Contains("E n c r y p t e d P a c k a g e"))\n return true;\n\n return false;\n }\n\n // Unknown format.\n return false;\n}\n
Run Code Online (Sandbox Code Playgroud)\n
归档时间: |
|
查看次数: |
8589 次 |
最近记录: |