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

标签 c# ms-word ms-office office-interop password-protection

我使用 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/

相关文章:

c# - .NET Core 上的 OpenFileDialog

python - .doc 到 pdf 使用 python

c# - 功能区 labelControl GetSuperTip 不起作用

c# - 无法将 Microsoft Office Interop 程序集添加到项目中

sql - 如何根据另一个字段中的查找值返回一个字段中的值

c# - 如何从其他 C# 项目调用 VSTO 类

c# - OwinStartupAttribute 不应该在 global.asax 和 Application_Start 之前运行吗?

c# - 将 DataGrid 列标题拖放到标签上?

c# - STL 集的 C# 等价物是什么?

java - 如何使用 Java 编辑 MS Word 文档?