我有以下代码片段。它可以工作(打开目录中的所有 Word 文档,然后关闭它们)...但是当我完全退出程序时,它不会自行清理。
我的意思是,如果我退出 VB.NET 应用程序后查看任务管理器,我会看到 WINWORD.EXE,即使它在我打开应用程序之前并不存在。
这是我的声明:
Dim WordApp As Microsoft.Office.Interop.Word.Application
Dim aDoc As Microsoft.Office.Interop.Word.Document
Dim missing As Object = System.Reflection.Missing.Value
Dim nullobj As Object = System.Reflection.Missing.Value
Dim MYreadOnly As Object = False
Dim isVisible As Object = False
这是代码:
Private Sub cmdGenerate_Click(sender As System.Object, e As System.EventArgs) Handles cmdGenerateKeywords.Click
Dim xmldoc As New XmlDataDocument()
Dim xmlnode As XmlNodeList
Dim i As Integer
Dim fs As FileStream
WordApp = New Microsoft.Office.Interop.Word.Application
WordApp.Visible = False
For Each f As FileInfo In New DirectoryInfo(txtFolderName.Text).GetFiles("*.docx")
' Open the document that was chosen by the dialog
aDoc = WordApp.Documents.Open(f.FullName, missing, [MYreadOnly], _
missing, missing, missing, missing, missing, missing, missing, _
missing, isVisible)
'aDoc.Close()
aDoc = Nothing
Next
'Close the Word Document
'aDoc.Close(nullobj, nullobj, nullobj)
WordApp.Application.Quit()
WordApp = Nothing
End Sub
正如您所知,我已经对有关关闭 Word 文档和 Word 应用程序本身的各种声明进行了评论和取消评论。我尝试过的任何方法似乎都无法摆脱那个讨厌的 WINWORD.EXE
好像有什么东西有锁,不会让它关闭?是这样吗?
最佳答案
显式运行垃圾收集器,如图所示in this article :
// Clean up the unmanaged Word COM resources by forcing a garbage
// collection as soon as the calling function is off the stack (at
// which point these objects are no longer rooted).
GC.Collect();
GC.WaitForPendingFinalizers();
// GC needs to be called twice in order to get the Finalizers called
// - the first time in, it simply makes a list of what is to be
// finalized, the second time in, it actually is finalizing. Only
// then will the object do its automatic ReleaseComObject.
GC.Collect();
GC.WaitForPendingFinalizers();
尽管上面有链接,但我的经验是运行一次就足够了。但第二次调用不会抛出错误,所以就这样做。
关于vb.net - 无法从 .NET 关闭 MS Word,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124871/