Check if file is in use

Posted on 2004-12-01
Last Modified: 2012-05-05

I want to check in my vb program if a specific file is in use. Only when the file isn't in use anymore, my program may continue?

Can somebody help?

Question by:Q-Tip
    1 Comment
    LVL 85

    Accepted Solution

    What you can do is attempt to open the file with exclusive read write access.  If the attempt fails, it must be in use by another process:

    Option Explicit

    Private Sub Command1_Click()
        If isFileInUse(Text1.Text) Then
            Label1.Caption = "File In Use"
            Label1.Caption = "File Available"
        End If
    End Sub

    Private Function isFileInUse(ByVal filename As String) As Boolean
        On Error GoTo openError
        isFileInUse = False ' assume it isn't locked
        If Dir(filename) <> "" Then
            ' attempt to get exclusive access to the file
            ' if exclusive access fails, we jump to openError:
            ' and return true
            Open filename For Binary Lock Read Write As #1
            Close #1
            MsgBox filename, vbCritical, "File Not Found"
        End If
        Exit Function

    isFileInUse = True
    End Function

    Write Comment

    Please enter a first name

    Please enter a last name

    We will never share this with anyone.

    Featured Post

    Course: HTML5 Mobile App Development with PhoneGap

    PhoneGap can help you leverage your already existing HTML5, JavaScript, and CSS skills in order to create and deploy cross-platform mobile apps.This program comprehensively covers HTML5 mobile app development from top to bottom.

    Suggested Solutions

    This article will show, step by step, how to integrate R code into a R Sweave document
    A short article about problems I had with the new location API and permissions in Marshmallow
    An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
    In this fourth video of the Xpdf series, we discuss and demonstrate the PDFinfo utility, which retrieves the contents of a PDF's Info Dictionary, as well as some other information, including the page count. We show how to isolate the page count in a…

    759 members asked questions and received personalized solutions in the past 7 days.

    Join the community of 500,000 technology professionals and ask your questions.

    Join & Ask a Question

    Need Help in Real-Time?

    Connect with top rated Experts

    14 Experts available now in Live!

    Get 1:1 Help Now