检查Word文件是否已打开

时间:2014-09-09 09:21:56

标签: vb.net ms-word

我有一个生成文档的应用程序。

但是,如果文档已经打开,则生成的新文档无法覆盖打开的文档,因此不会发生任何更改。

如何正确检查文档是否已打开? (如果打开,那么关闭它)

2 个答案:

答案 0 :(得分:2)

您可以尝试这样:

 If File.Exists(Application.StartupPath & "\~$MyWordDocument.doc") Then
   MsgBox("File is open")
   Exit Sub
End If

同时检查FAQ: How do I check whether a file is in use?

答案 1 :(得分:2)

此代码对我有用

Public Function FileInUse(ByVal sFile As String) As Boolean
     Dim thisFileInUse As Boolean = False
     If System.IO.File.Exists(sFile) Then
         Try
           Using f As New IO.FileStream(sFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None)
                    ' thisFileInUse = False
           End Using
         Catch
           thisFileInUse = True
         End Try
     End If
     Return thisFileInUse
    End Function