我想检查C:\ Data.xlsb是否已经打开。
我从这里获得了以下代码How to tell if a certain Excel file is open using 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。
最好的问候。
答案 0 :(得分:1)
您应该将返回类型更改为Boolean
以更好地满足您的需求,并且还要从StreamWriter
切换为FileStream
。这是因为在帖子中你链接了OP想写的文件,我认为你不想要(或者至少不使用纯文本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
请注意,任何一项功能只会告诉您文件是否可访问,进程是否可以在不锁定的情况下打开它。
答案 1 :(得分:0)
要使用此代码,您可以使用以下示例中的函数:
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,那么您将知道该文件已被锁定。
请注意,您还需要
Imports System.IO
让这个例子起作用。