Sandro Bizioli


Chi sogna di giorno conosce molte cose che sfuggono a chi sogna soltanto di notte. (E.A.Poe)
Mappa

Verificare se un file è aperto in modo esclusivo.

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

Categoria: VB6
lunedì, 05 mar 2007 Ore. 17.23
Statistiche
  • Views Home Page: 109.878
  • Views Posts: 560.122
  • Views Gallerie: 108.931
  • n° Posts: 227
  • n° Commenti: 222
Copyright © 2002-2007 - Blogs 2.0
dotNetHell.it | Home Page Blogs
ASP.NET 2.0 Windows 2003