Word.Application.Quit()函数不起作用

本文关键字:函数 不起作用 Application Quit Word | 更新日期: 2023-09-27 18:24:44

我正在开发一个应用程序,在该应用程序中,我必须将Word(.doc)文件转换为文本文件,下面是代码示例:

//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);

但是当我尝试使用以下代码读取temp.txt文件的内容时,我的应用程序没有正确关闭

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

它抛出这个异常

进程无法访问文件"F:''wordDoc''wordDoc''bin''Debug''temp.txt",因为另一个进程正在使用该文件。

有人能告诉我怎么修吗?

Word.Application.Quit()函数不起作用

在尝试打开文件之前,请尝试使用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);
}