2016-02-28 31 views
0

我正在使用以下代碼來讀取(本地)網站上傳的word文件。無法讀取mvc中的word文件4

List<string> ReadWordFile(string path) 
{ 
     Application word = new Application(); 
     Document doc = new Document(); 

     ((_Document)doc).Close(); 
     ((_Application)word).Quit(); 

     List<string> data = new List<string>(); 
     try 
     { 
      object fileName = path; 
      // Define an object to pass to the API for missing parameters 
      object missing = System.Type.Missing; 
      doc = word.Documents.Open(ref fileName, 
        ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing, ref missing, 
        ref missing, ref missing, ref missing); 

      String read = string.Empty; 
      for (int i = 0; i < doc.Paragraphs.Count; i++) 
      { 
       string temp = doc.Paragraphs[i + 1].Range.Text.Trim(); 
       if (temp != string.Empty) 
        data.Add(temp); 
      } 
     } 
     catch (Exception) 
     { 

     } 
     finally { 

      ((_Document)doc).Close(); 
      ((_Application)word).Quit(); 
     } 

     return data; 
} 

這是錯誤:

The object invoked has disconnected from its clients. (Exception from HRESULT: 0x80010108 (RPC_E_DISCONNECTED)) 

我打電話從我的控制器此功能。如果我正在以錯誤的方式閱讀文件,那麼正確的方法是什麼?

回答

0

不要關閉Word你開始做某件事之前:

刪除線6和7:

((_Document)doc).Close(); 
    ((_Application)word).Quit(); 

,在finaly部分,所以沒必要把它背在你已經做結束。

+0

哇謝謝!儘管我後來放了這條線,因爲我收到了一些其他錯誤,但我不知道爲什麼現在突然工作。但無論什麼幫助。謝謝 –