2014-09-28 651 views
0

我開發在我所到Word(.DOC)將文件轉換爲文本文件中的應用,這裏是代碼示例:Word.Application.Quit()功能無法正常工作

//Creating the instance of Word Application 
Word.Application newApp = new Word.Application(); 

// specifying the Source & Target file names 
object Source = "F:\\wordDoc\\wordDoc\\bin\\Debug\\word.docx"; 
object Target = "F:\\wordDoc\\wordDoc\\bin\\Debug\\temp.txt"; 
object readOnly = true; 
// Use for the parameter whose type are not known or 
// say Missing 
object Unknown = Type.Missing; 

// Source document open here 
// Additional Parameters are not known so that are 
// set as a missing type; 
newApp.Documents.Open(ref Source, ref Unknown, 
    ref readOnly, ref Unknown, ref Unknown, 
    ref Unknown, ref Unknown, ref Unknown, 
    ref Unknown, ref Unknown, ref Unknown, 
    ref Unknown, ref Unknown, ref Unknown, ref Unknown); 

// Specifying the format in which you want the output file 
object format = Word.WdSaveFormat.wdFormatDOSText; 
object orgfrmat = Word.WdSaveFormat.wdFormatFilteredHTML; 
//Changing the format of the document 
newApp.ActiveDocument.SaveAs(ref Target, ref format, 
     ref Unknown, ref Unknown, ref Unknown, 
     ref Unknown, ref Unknown, ref Unknown, 
     ref Unknown, ref Unknown, ref Unknown, 
     ref Unknown, ref Unknown, ref Unknown, 
     ref Unknown, ref Unknown); 

// for closing the application 
object saveChanges = Word.WdSaveOptions.wdSaveChanges; 
newApp.Quit(ref saveChanges, ref Unknown, ref Unknown); 

,但我的應用程序沒有正確關閉,當我嘗試使用此代碼

using (StreamReader sr = new StreamReader("F:\\wordDoc\\wordDoc\\bin\\Debug\\temp.txt")) 
{ 
    rtbText.Text = sr.ReadToEnd(); 
    // Console.WriteLine(line); 
} 

它拋出該異常

該進程無法訪問讀取TEMP.TXT文件的內容文件'F:\ wordDoc \ wordDoc \ bin \ Debug \ temp.txt',因爲它正在被另一個進程使用。

誰能告訴我如何解決它?

+2

那麼,爲什麼你認爲Word不關閉? 2個代碼片段之間的關係(時間)是什麼? – 2014-09-28 10:31:55

+0

,因爲temp.txt已經在使用,兩個代碼都在同一個按鈕點擊事件 – 2014-09-28 10:38:46

回答

3

嘗試使用Marshal.ReleaseComObject在嘗試打開文件之前清理COM對象。

例如。

object saveChanges = Microsoft.Office.Interop.Word.WdSaveOptions.wdSaveChanges; 
newApp.Quit(ref saveChanges, ref Unknown, ref Unknown); 

Marshal.ReleaseComObject(newApp); 

using (StreamReader sr = new StreamReader((string)Target)) 
{ 
    Console.WriteLine(sr.ReadToEnd()); 
} 

或者,爲了避免使用COM(並且需要安裝Office),您可以使用第三方庫。我對這個圖書館沒有經驗http://docx.codeplex.com/,但是對於一個簡單的測試,它似乎完成了這項工作。如果您的文件格式複雜,則可能無法爲您工作。

string source = @"d:\test.docx"; 
string target = @"d:\test.txt"; 

// load the docx 
using (DocX document = DocX.Load(source)) 
{ 
    string text = document.Text; 

    // optionally, write as a text file 
    using (StreamWriter writer = new StreamWriter(target)) 
    { 
     writer.Write(text);   
    } 

    Console.WriteLine(text); 
} 
+0

謝謝你的工作,反正有沒有使用Word.Application將.doc轉換爲.text? – 2014-09-28 10:45:53

+0

我已經編輯了答案,以包括一個替代..我沒有在實踐中使用這個第三方庫,但一個簡單的測試工作。 – steve16351 2014-09-28 10:57:57

+0

謝謝@steve我也會試試這個 – 2014-09-29 02:01:14