2014-10-07 82 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