Detect password protected word file

2019-02-15 15:15发布

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条回答
混吃等死
2楼-- · 2019-02-15 16:13

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();
        }
查看更多
登录 后发表回答