Detect password protected word file

谁说我不能喝 提交于 2019-11-30 19:06:29

问题


I am using "netoffice" library for extracting the text from word files. This should be automated process.

However, when the word file is password protected, the alert windows is shown so the user needs to enter the password. Because this is automated process, the user does not enters the password, and the program stops here.

How can I detect if the word file is password protected with "netoffice", and if this is not possible, how can I disable the alert windows from showing up?

I tried setting DisplayAlerts to WdAlertLevel.wdAlertsNone, but it isn't working.


回答1:


The following piece of code will help you skip password-protected files:

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


来源:https://stackoverflow.com/questions/26235417/detect-password-protected-word-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!