无法关闭来自.NET的MS Word

时间:2013-02-27 23:50:26

标签: vb.net ms-word

我有以下代码段。它工作(打开目录中的所有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

有些东西似乎有锁并且不会让它关闭?是吗?

2 个答案:

答案 0 :(得分:2)

显式运行垃圾收集器,如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();

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

答案 1 :(得分:0)

fs.Close()
fs.Dispose()

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

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