[dba-VB] Detecting an Open File

MartyConnelly martyconnelly at shaw.ca
Mon Sep 29 14:49:48 CDT 2003


if you know the filename you could try
This is from MSKB Last reviewed: August 1, 1997 Article ID: Q172240 
but they seem to have removed the KB article.
 Note if you try this with Notebook to open the file, Notebook only 
takes a copy and then releases the file.


The function described here is called IsFileAlreadyOpen, declared as:

     Function IsFileAlreadyOpen(Filename As String) As BOOLEAN

If this function returns TRUE, then the file is already open. It 
determines that the file is already open only if it gets 
ERROR_SHARING_VIOLATION when it attempts to open the file.

It will return FALSE in the following conditions:

- The file is not already open.

- The calling application does not have access to the file due to NTFS
  security.

- The file does not exist.

You should check if the file exists before calling the function to  
eliminate the possibility of the latter condition.

Sample Code: Microsoft Visual Basic version of IsFileAlreadyOpen
----------------------------------------------------------------

     ' Declaration for APIs used by our function...
     Private Declare Function lopen Lib "kernel32" Alias "_lopen" (ByVal
     lpPathName As String, ByVal iReadWrite As Long) As Long
     Private Declare Function GetLastError Lib "kernel32" () As Long
     Private Declare Function lclose Lib "kernel32" Alias "_lclose" (ByVal
     hFile As Long) As Long

     ' Our Function...
     Function IsFileAlreadyOpen(Filename As String) As Boolean
        Dim hFile As Long
        Dim lastErr As Long

        ' Initialize file handle and error variable.
        hFile = -1
        lastErr = 0

        ' Open for for read and exclusive sharing.
        hFile = lopen(Filename, &H10)

        ' If we couldn't open the file, get the last error.
        If hFile = -1 Then
           lastErr = Err.LastDllError
        ' Make sure we close the file on success.
        Else
           lclose (hFile)
        End If

        ' Check for sharing violation error.
        If (hFile = -1) And (lastErr = 32) Then
           IsFileAlreadyOpen = True
        Else
           IsFileAlreadyOpen = False
        End If


Bill Kollodge wrote:

> Can anyone tell me how to detect if a specific file number is already 
> open (besides dealing with the error 55 which results)?
>
> Bill Kollodge
> New Product Development
> Park Industries
> St. Cloud, MN
> 320-251-5077
> bkollodge at parkindustries.com
>
>------------------------------------------------------------------------
>
>_______________________________________________
>dba-VB mailing list
>dba-VB at databaseadvisors.com
>http://databaseadvisors.com/mailman/listinfo/dba-vb
>http://www.databaseadvisors.com
>
>  
>




More information about the dba-VB mailing list