2

我有以下代码片段。它可以工作(打开目录中的所有 Word 文档,然后将它们关闭)......但是当我完全退出程序时它不会自行清理。

我的意思是,如果我在退出 VB.NET 应用程序后查看 TaskManager,我会看到 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

有些东西似乎有锁,不会让它关闭?是这样吗?

4

2 回答 2

2

显式运行垃圾收集器,如本文所示:

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

尽管有上面的链接,但我的经验是运行一次就足够了。但是第二次调用不会抛出错误,所以这样做。

于 2013-07-12T14:03:18.170 回答
0
fs.Close()
fs.Dispose()

http://msdn.microsoft.com/en-us/library/system.io.filestream.dispose.aspx

这会释放您的资源。可能允许其他关闭方法起作用。我通读了两次代码,并没有看到您像我期望的那样在任何地方使用“fs”。

于 2013-07-12T12:19:47.543 回答