Ecco un paio di sistemi molto semplici per verificare se è possibile accedere ad un file o se questo è stato aperto in modo esclusivo da qualche altra applicazione.
I sorgenti sono compatibili con Visual Basic 5 e Visual Basic 6
La prima funzione sfrutta le consuete API di Windows:
Private Const GENERIC_READ As Long = &H80000000
Private Const INVALID_HANDLE_VALUE As Long = -1
Private Const OPEN_EXISTING As Long = 3
Private Const FILE_ATTRIBUTE_NORMAL As Long = &H80
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
Private Function isFileInUSe(ByVal miofile As String) As Boolean
Dim hFile As Long
hFile = CreateFile(miofile, GENERIC_READ, 0, 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0&)
isFileInUSe = hFile = INVALID_HANDLE_VALUE
CloseHandle(hFile)
End Function
La seconda, invece, utilizza il semplice metodo File Open impostando il lock su lettura.
Private Function isFileInUSe_noApi(ByVal mioFile As String) As Boolean
Dim nFree As Integer
nFree = FreeFile()
On Error Resume Next
Open mioFile For Input Lock Read As #nFree
isFileInUSe_noApi = Not (Err.Number = 0)
If Err.Number <> 0 Then Err.Clear()
Close #nFree
End Function