gpt4 book ai didi

vb.net - 检查excel文件是否被其他用户打开

转载 作者:行者123 更新时间:2023-12-02 03:54:28 25 4
gpt4 key购买 nike

我在服务器上有一个 Excel 文件。

我正在使用VB.NET编写的应用程序以只读模式打开文件。

用户 1 以只读模式打开文件。用户2如何检测文件是否打开状态?

谢谢,一个

最佳答案

您需要测试文件是否为只读,因为如果文件处于只读状态,则读写会失败。下面介绍一些方法。除了兰迪·伯奇(Randy Birch)的最后一张之外,不知道我从哪里得到它们。速度测试有利于 FileIsOpen3 和 FileIsOpen4。

Function FileIsOpen1(ByVal pathfile As String) As Boolean
Dim ff As Integer
If System.IO.File.Exists(pathfile) Then
Try
ff = FreeFile()
Microsoft.VisualBasic.FileOpen(ff, pathfile, OpenMode.Binary, OpenAccess.Read, OpenShare.LockReadWrite)
Return False
Catch
Return True
Finally
FileClose(ff)
End Try
Return True
End If
End Function

Function FileIsOpen2(ByVal pathfile As String) As Boolean
Dim stream As FileStream = Nothing
Dim fi As FileInfo = Nothing
If System.IO.File.Exists(pathfile) Then
Try
fi = New System.IO.FileInfo(pathfile)
stream = fi.Open(FileMode.Open, FileAccess.Read, FileShare.None)
Return True
Catch generatedExceptionName As IOException
Return False
Finally
If stream IsNot Nothing Then
stream.Close()
End If
fi = Nothing
End Try
Return True
End If
End Function

Private Function FileIsOpen3(ByVal pathfile As String) As Boolean
Try
Dim fs As IO.FileStream = IO.File.Open(pathfile, IO.FileMode.Open, IO.FileAccess.Read, IO.FileShare.None)
fs.Close()
fs.Dispose()
fs = Nothing
Return False
Catch ex As IO.IOException ' File open
Return True
Catch ex As Exception ' Unknown error
Return True
End Try
End Function

Private Declare Function CreateFile Lib "kernel32" _
Alias "CreateFileA" _
(ByVal lpFileName As String, _
ByVal dwDesiredAccess As Long, _
ByVal dwShareMode As Long, _
ByVal lpSecurityAttributes As Long, _
ByVal dwCreationDisposition As Long, _
ByVal dwFlagsAndAttributes As Long, _
ByVal hTemplateFile As Long) As Long
Private Declare Function CloseHandle Lib "kernel32" _
(ByVal hFile As Long) As Long

' Method
Shared Function FileIsOpen4(ByVal pathfile As String) As Boolean
' Is File In Use ©1996-2009 Randy Birch
' http://vbnet.mvps.org/index.html?code/fileapi/createfile_inuse.htm
Const GENERIC_READ As Long = &H80000000
Const INVALID_HANDLE_VALUE As Long = -1
Const OPEN_EXISTING As Long = 3
Const FILE_ATTRIBUTE_NORMAL As Long = &H80
Dim hFile As Long

If System.IO.File.Exists(pathfile) Then
Try
' note that FILE_ATTRIBUTE_NORMAL (&H80) has a different value than VB's constant vbNormal (0)!
hFile = CreateFile(pathfile, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0&)
' this will evaluate to either -1 (File in use) or 0 (File free)
Return hFile = INVALID_HANDLE_VALUE
Catch ex As Exception
MessageBox.Show(ex.ToString)
Finally
CloseHandle(hFile)
End Try
Else
Return True
End If
End Function

关于vb.net - 检查excel文件是否被其他用户打开,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2550560/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com