c# - 检测密码保护的word文件

标签 c# parsing ms-word netoffice

我正在使用“netoffice”库从 word 文件中提取文本。这应该是自动化过程。

但是,当 word 文件受密码保护时,会显示警告窗口,因此用户需要输入密码。因为这是自动化过程,用户没有输入密码,程序就在这里停止。

我如何检测 word 文件是否受“netoffice”密码保护,如果这不可能,我如何禁止显示警告窗口?

我尝试将 DisplayAlerts 设置为 WdAlertLevel.wdAlertsNone,但它不起作用。

最佳答案

以下代码将帮助您跳过受密码保护的文件:

        int iFilesWithPassword = 0;
        Factory.Initialize();
        Application wordApplication = new NetOffice.WordApi.Application();

        try
        {
            // Attempt to open existing document. If document is not password protected then 
            // passwordDocument parameter is simply ignored. If document is password protected
            // then an error is thrown and caught by the catch clause the follows, unless 
            // password is equal to "#$nonsense@!"!                              
            Document newDocument = wordApplication.Documents.Open(@"C:\Users\Giorgos\Desktop\myNextFile.doc",
                                                                  confirmConversions: false,
                                                                  addToRecentFiles: false,
                                                                  readOnly: false,
                                                                  passwordDocument: "#$nonsense@!");



            // read text of document
            string text = newDocument.Content.Text;
        }
        catch(Exception e)
        {
            Exception inner = e.InnerException;

            if (inner != null && inner.InnerException != null)
            {
                inner = inner.InnerException;
                string sErrorMessage = inner.Message;

                if (sErrorMessage.Contains("The password is incorrect."))
                {
                    iFilesWithPassword++;
                }
            }

        }
        finally
        {
            // close word and dispose reference 
            wordApplication.Quit();
            wordApplication.Dispose();
        }

关于c# - 检测密码保护的word文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26235417/

相关文章:

c# - OleDbDataAdapter .Update 方法未保留架构更改

c# - 有没有办法解决设计时伪错误或让 IDE 忽略它们?

parsing - 投影文本编辑器?

c++ - 解析时即时收集类定义

vba - 字 VBA : Get Range between Consecutive Headings

c# - 如何使用触摸板 gearVR

c# - 从点数组平滑二维线

performance - 在golang中解析日期和时间的最佳方式

javascript - 替换多个文档中的部分 HTML 字符串

delphi - 如何将参数传递给 OLE 自动化对象(例如 MS Word)