2014-09-28 653 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