我正在开发一个应用程序,我必须将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'因为它正被另一个进程使用。
有谁能告诉我如何解决它?
答案 0 :(得分:4)
尝试使用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);
}