Results 1 to 4 of 4

Thread: Is file in use?

  1. #1

    Thread Starter
    Junior Member
    Join Date
    Jan 1999
    Location
    Scarsdale, NY
    Posts
    26

    Question

    Hi!

    Can anyone please tell me how to perform a simple check on a file - if it is in use or not. I can't afford to be opening files from my program to get error msgs and therefore assume that files are being used. Is there an API that does it?

    Thank you!!!!

  2. #2
    Frenzied Member Jop's Avatar
    Join Date
    Mar 2000
    Location
    Amsterdam, the Netherlands
    Posts
    1,986
    I can't afford to be opening files from my program to get
    error msgs and therefore assume that files are being used.
    Why not? I think the error message "File already open" can only mean one thing (maybe I'm wrong) namely that's in use with another app.
    I think it's a pretty save way to assume the file is in use by trapping this error.

    But if you really need the api way you'll probably find something at allapi.net, vbaccelerator.com or VBnet (http://www.mvps.org/vbnet/)
    I couldn't find something it my api-viewer though
    Jop - validweb.nl

    Alcohol doesn't solve any problems, but then again, neither does milk.

  3. #3
    Guest
    Try this:

    Code:
    Private Declare Function lOpen Lib "kernel32" Alias "_lopen" (ByVal lpPathName As String, ByVal iReadWrite As Long) As Long
    Private Declare Function lClose Lib "kernel32" Alias "_lclose" (ByVal hFile As Long) As Long
    
    
    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
        Else
        ' Make sure we close the file on success.
        lClose (hFile)
     End If
    
     ' Check for sharing violation error.
     If (hFile = -1) And (lastErr = 32) Then
        IsFileAlreadyOpen = True
        Else
        IsFileAlreadyOpen = False
     End If
    End Function
    
    
    'Usage:
    
    Private Sub Command1_Click()
    If IsFileAlreadyOpen("C:\program.exe") Then
    MsgBox "File open!"
    Else
    MsgBox "File not open!"
    End If
    End Sub

  4. #4

    Thread Starter
    Junior Member
    Join Date
    Jan 1999
    Location
    Scarsdale, NY
    Posts
    26

    Is File in Use?

    Matthew,

    Unfortunately your code didn't work. I had a file opened while my program ran, and the program did not detect it...
    I'm running WinNT (if it matters).

    Would you have any other suggestions?

    Many thanks.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width