2014-10-07 84 views
2

我使用“netoffice”库从文件中提取文本。这应该是自动化的过程。检测密码保护字文件

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

如何检测word文件是否使用“netoffice”进行密码保护,如果不能这样做,如何禁用警报窗口显示?

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

回答

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 "#[email protected]!"!        
      Document newDocument = wordApplication.Documents.Open(@"C:\Users\Giorgos\Desktop\myNextFile.doc", 
                    confirmConversions: false, 
                    addToRecentFiles: false, 
                    readOnly: false, 
                    passwordDocument: "#[email protected]!"); 



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

以前一样,显示警告窗口。 – Programmer 2014-10-07 16:10:27

+0

我在VS2012中制作了一个控制台应用程序,使用.NET Framework 4.0和NetOffice.dll v1.6。如果我省略passwordDocument参数,我也会收到密码提示对话框。如果我添加passwordDocument参数,则不会显示对话框并引发异常。 – 2014-10-07 17:03:07

+1

不知道如果[程序员](http://stackoverflow.com/users/2096420)的评论需要删除,因为该答案的接受答案状态,但我可以确认此脚本的VBS版本确实可以[giorgos -betsos](http://stackoverflow.com/users/2149718)建议。 – user66001 2017-03-08 15:36:25