这是我添加的旧帖子,但最近我想确定电子表格是否在 C# 中受到密码保护而不使用外部库,我最终创建了以下代码。
可能有一些我没有找到的案例和文件格式,但我希望这会让你走上正轨。
注意:比较文本中的空格数很重要,因此在剪切和粘贴时要小心。
static bool IsExcelPasswordProtected(string strSource)
{
bool blResult = false;
if (File.Exists(strSource))
{
char[] chBuffer = new char[4096]; // The character strings usually occur within the first 2K in my testing, but just in case
TextReader trReader = new StreamReader(strSource, Encoding.UTF8, true);
// Read the buffer
trReader.ReadBlock(chBuffer, 0, chBuffer.Length);
trReader.Close();
// Remove non-printable and unicode characters, we're only interested in ASCII character set
for (int i = 0; i < chBuffer.Length; i++)
{
if ((chBuffer[i] < ' ') || (chBuffer[i] > '~')) chBuffer[i] = ' ';
}
string strBuffer = new string(chBuffer);
// .xls format files, version 97 to 2003 contains this text when password protected
if (strBuffer.Contains("M i c r o s o f t E n h a n c e d C r y p t o g r a p h i c P r o v i d e r"))
{
blResult = true;
}
// .xlsx format files contain this text when password protected
else if (strBuffer.Contains("E n c r y p t e d P a c k a g e"))
{
blResult = true;
}
// .xlsx format files contain this text when not password protected
else if (strBuffer.Contains("[Content_Types]"))
{
blResult = false;
}
// .xlsx format files contain this text when not password protected
else
{
blResult = false;
}
}
else
{
// File not found...deal with as you wish
}
return (blResult);
}