有没有一种方法可以检查文件是否已经打开?

我想检查C:\ Data.xlsb是否已经打开。

我从这里有下面的代码如何判断某个Excel文件是否使用VB.NET打开?

Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter Dim sw As StreamWriter = nothing Try sw = New StreamWriter(path) Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32 REM locked, return nothing End Try Return sw End Function 

但是我不知道如何使用上面的代码。

我更喜欢sub而不是function。

最好的祝福。

要使用这个代码,你可以使用如下例所示的函数:

 Imports System.IO Public Class Form1 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click If OpenUnlockedFile("C:\Data.xlsb") Is Nothing Then MessageBox.Show("File is locked") End If End Sub Public Shared Function OpenUnlockedFile(ByVal path As String) As StreamWriter Dim sw As StreamWriter = Nothing Try sw = New StreamWriter(path) Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32 REM locked, return nothing End Try Return sw End Function End Class 

只要按下Button1(在本例中),就会运行OpenUnlockedFile(“C:\ Data.xlsb”)函数。 如果函数运行并且它返回Nothing,那么你将知道文件被locking。

请注意,你也需要

 Imports System.IO 

为这个例子工作。

您应该将返回types更改为Boolean以更好地满足您的需要,并且也可以从StreamWriter切换到FileStream 。 这是因为在链接OP想要写入文件,我不认为你想(或至less不使用纯文本StreamWriter )的文章。

 Public Shared Function IsFileAvailable(ByVal path As String) As Boolean Try Dim fs As New FileStream(path, FileMode.Open, FileAccess.Read, FileShare.None) fs.Close() Catch ex As IOException When System.Runtime.InteropServices.Marshal.GetLastWin32Error() = 32 Return False End Try Return True End Function 

那么你可以像这样使用它:

 If IsFileAvailable("C:\Data.xlsb") = True Then 'File is not locked, do what you like here. Else MessageBox.Show("The file is locked!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error) End If 

请注意,任何一个函数只会告诉你文件是否可访问,有可能是一个进程打开它而不locking它。