问题描述
我正在开发一个允许用户上传不同文件格式的网站.我们需要限制用户上传受密码保护的文件.
I am working on a website, which allows users to upload different file formats. We need to restrict the user from uploading password protected files.
有没有办法在上传文件之前确定 Microsoft Office 文件(Word、Powerpoint 和 Excel)是否受密码保护?根据 http://social.msdn.microsoft.com/Forums/en/oxmlsdk/thread/34701a34-f1d4-4802-9ce4-133f15039c69,我已经实现了以下内容,但它在尝试打开时抛出错误文件包含损坏的数据"受密码保护的文件.
Is there a way to determine if a Microsoft Office file (Word, Powerpoint & Excel) is password protected before uploading the file? As per http://social.msdn.microsoft.com/Forums/en/oxmlsdk/thread/34701a34-f1d4-4802-9ce4-133f15039c69, I have implemented the following, but it throws an error saying "File contains corrupted data", while trying to open a password protected file.
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;
}
}
是否有其他方法可以确定这一点?
Are there any other ways to determine this?
推荐答案
试试这个代码:
public static Boolean IsProtected(String file)
{
Byte[] bytes = File.ReadAllBytes(file);
String prefix = Encoding.Default.GetString(bytes.Take(2).ToArray());
// Zip and not password protected.
if (prefix == "PK")
return false;
// Office format.
if (prefix == "ÐÏ")
{
// XLS 2003
if (bytes.Skip(0x208).Take(1).ToArray()[0] == 0xFE)
return true;
// XLS 2005
if (bytes.Skip(0x214).Take(1).ToArray()[0] == 0x2F)
return true;
// DOC 2005
if (bytes.Skip(0x20B).Take(1).ToArray()[0] == 0x13)
return true;
// Guessing
if (bytes.Length < 2000)
return false;
// DOC/XLS 2007+
String start = Encoding.Default.GetString(bytes.Take(2000).ToArray()).Replace(" ", " ");
if (start.Contains("E n c r y p t e d P a c k a g e"))
return true;
return false;
}
// Unknown format.
return false;
}
这篇关于如何在将文件上传到服务器之前检测 Word 文档是否受密码保护?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!