2017-07-29 46 views
1

以下是我的代碼。但密碼不會被刪除。當我手動打開Word時,密碼對話框仍然彈出。如何使用Interop在c中刪除Word密碼#

我也嘗試了Unprotect方法,但那也行不通。

private static void WordUnProtect(string fileName, string password) 
    { 
     var app = new Word.Application(); 
     Word.Document doc = null; 

     try 
     { 
      doc = app.Documents.Open(fileName, PasswordDocument: password); 

      // this doesn't work also 
      //doc.Unprotect(); 

      doc.Password = string.Empty; 

      doc.Save(); 
     } 
     finally 
     { 
      if (doc != null) 
      { 
       doc.Close(false); 
       Marshal.ReleaseComObject(doc); 
      } 

      if (app != null) 
      { 
       app.Quit(); 
       Marshal.ReleaseComObject(app); 
      } 
     } 
    } 
+0

也許嘗試相當於_save as_。這就是用戶通常以交互方式使用Word時的做法 – MickyD

回答

2

它看起來像設置Password財產實際上並不文檔標註爲,所以它不會被保存。我已經瀏覽了文檔,看看是否有一個選項強制它保存/反正它變髒。我找不到,但我隱約記得,這種選擇存在於早期版本的Word自動化模型中。

所以我想出了這個小小的黑客來對文檔做一個小改動,但同時也刪除了這個改變。

// doc IsDirty 
doc.Range(0, 0).InsertBefore(" "); 
// no more password 
doc.Password = null; 
// let's remove what was Inserted 
doc.Range(0, 1).Text =""; 

另一種選擇當然是做SaveAs由MickyD的建議,但隨後你需要寫一個臨時文件,關閉並正確地釋放使原來的文件不再被鎖定,刪除原始和移動tempfile爲原始文件。這將起作用,感覺它有更多的失敗案例。

+0

Thx for the hack! –

相關問題