gpt4 book ai didi

c# - 无需打开即可检查 Word 文档是否受密码保护

转载 作者:行者123 更新时间:2023-12-02 04:10:31 24 4
gpt4 key购买 nike

我使用 Microsoft Office Interop 命名空间来用密码保护 Word 文档。我首先创建一个 Word 实例作为后台进程,并收集我想要保护的 Word 文档列表。我遇到的问题是,当应用程序访问一个已经安全的文档时,它会打开并提示输入设置的密码。忽略此操作后,它会运行其余文档,并且 Word 实例现在位于前台。

我想跳过以前 protected 文档。我的代码目前如下:

    private void Protect_Word(FileInfo file)
{
Word.Document doc = wrd.Documents.Open(file.FullName);
if (!doc.HasPassword)
{
doc.Password = this.passwordBox.Text;
doc.Save();

}
((Microsoft.Office.Interop.Word._Document)doc).Close(0);
}

此设置的问题是,在调用 HasPassword 之前,需要输入文档的密码。有没有办法在实际打开文档之前以编程方式检查文档的密码?

最佳答案

也遇到这个问题...我想出了“肮脏的解决方案” - 为“Word”(或Excel)传递无效的密码,如果文档带有密码,WINWORD.EXE将处理此选项,将尝试应用于文档,密码不匹配,将生成一个 COM 异常,我们捕获该异常并使用密码了解该文档!否则,如果文档没有密码,字处理器本身会忽略传输的密码(我实验检查后明白了......)

        Word.Application app = null;
Word.Documents docs = null;
try
{
app = new Word.Application();
app.Visible = false;
docs = app.Documents;
// перебираем список файлов
for (int i = 0; i < listFilesWord.Count; i++)
{
Word.Document doc = null;
try
{
doc = docs.Open(
listFilesWord[i].FullName,
Word.WdSaveFormat.wdFormatDocument,
(object)false,
Type.Missing,
" ",
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
Type.Missing,
(object)false,
Type.Missing,
Type.Missing,
(object)true,
Type.Missing);
doc.Save();
doc.Close();
}
catch (COMException ex)
{
Console.WriteLine(ex.Message);
}
finally
{
if (doc != null) Marshal.ReleaseComObject(doc);
}
}
app.Quit();
}
finally
{
if (docs != null) Marshal.ReleaseComObject(docs);
if (app != null) Marshal.ReleaseComObject(app);
}

关于c# - 无需打开即可检查 Word 文档是否受密码保护,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37190539/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com