检测受密码保护的word文件

时间:2014-10-07 11:55:17

标签: c# parsing ms-word netoffice

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

但是,当word文件受密码保护时,会显示警告窗口,因此用户需要输入密码。由于这是自动过程,因此用户不输入密码,程序将在此处停止。

如何使用" netoffice"检测word文件是否受密码保护,如果无法做到这一点,如何禁用警报窗口显示?

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

1 个答案:

答案 0 :(得分:1)

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

        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();
        }