通过使用C#终止winword进程再次打开单词文件时正在使用的文件 [英] File in use when opening the word file again that was closed by killing the winword process using C#

查看:135
本文介绍了通过使用C#终止winword进程再次打开单词文件时正在使用的文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们使用Microsoft.Office.Interop.Word.Application以编程方式打开word文档。我们更新文档,然后保存并关闭文档。它工作正常,但有时它无法关闭文档并退出应用程序(就像在文档上打开一些需要人工干预的对话框)。



对于这种情况,我们需要删除用于打开文档的单词进程,以便我们可以处理其他文档。



我发现这个解决方案文件被c sharp中的另一个进程使用 [ ^ ]



使用代码,我能够找到该进程,然后调用process.kill()方法来终止winword进程。它会删除该文件,但是如果我再次尝试打开该文件,它会弹出使用中的文件对话框。



如何摆脱这个?请帮助

We open the word document programatically using Microsoft.Office.Interop.Word.Application. We update the document and then save it and close the document. It works fine but occassionally it is not able to close the document and quit the application (like if some dialog opens on the document requiring human intervention).

For such situation, we need to kill the word process that was used to open the document so that we can process other documents.

I found this solution file is used by another process in c sharp[^]

Using the code, I am able to find the process and then call process.kill() method to kill the winword process. It deletes the file, however if I try to open the file again, it pops up the File In Use dialog.

How to get away with this? Please help

推荐答案

使用Process.Kill()不是关闭应用程序的正确方法。



您可能无法正确释放所有实例化的COM对象。



调用退出或退出方法后跟COM对象上的Dispose方法不会释放所有引用。



请参阅如何释放COM互操作对象,以便被叫程序可以退出 [ ^ ]



Using Process.Kill() is not the proper way to shutdown an application.

You may not be properly releasing all of the instantiated COM objects.

Calling a "Quit" or "Exit" method followed by a "Dispose" method on a COM object will not free up all of the references.

See How to Release COM Interop Objects so the Called Program Can Exit[^]

// Call Quit() Method to start Word shutdown process
oApp.Quit();
Application.DoEvents();
//
// This sample has only one COM object declared.
//
// For programs with multiple COM objects declared, repeat the following four
// lines of code for each COM object in reverse order of creation.
//
while (System.Runtime.InteropServices.Marshal.ReleaseComObject(oApp) != 0) {
    Application.DoEvents();
}
oApp = null; // Set each COM Object to null
//
//
// After all of the COM objects have been released and set to null, do the following:
GC.Collect(); // Start .NET CLR Garbage Collection
GC.WaitForPendingFinalizers(); // Wait for Garbage Collection to finish

这篇关于通过使用C#终止winword进程再次打开单词文件时正在使用的文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆