What's New
Q & A
Tip Jar
C# Helper...
Follow VBHelper on Twitter
MSDN Visual Basic Community
TitleSee if a file is locked in Visual Basic .NET
DescriptionThis example shows how to see if a file is locked in Visual Basic .NET.
Keywordsfile locked, file, locked, VB.NET
CategoriesFiles and Directories
Some applications lock files so you cannot write, read, delete, or otherwise mess with them. For example, when you open a file in Word, it locks the file so you cannot delete it or open it for writing with a Visual Basic application.

Function FileIsLocked returns True if a file is locked for a certain kind of access. For example, pass this routine the access value FileAccess.Write if you want to see whether the file is locked to prevent you from writing into it.

The function uses an On Error Resume Next statement to protect itself (On Error is usually a lot faster than Try Catch and in this case we expect an error a significant amount of the time so the performance is important). It then tries to make a stream that opens the file for the desired access. If there is no error, the function returns False. If there is a file access error, the function returns True. If there is some other kind of error, the function re-raises the error and lets the calling code deal with it.

' Return True if the file is locked to prevent the desired
' access.
Private Function FileIsLocked(ByVal filename As String, _
    ByVal file_access As FileAccess) As Boolean
    Const FILE_LOCKED As Integer = 57

    On Error Resume Next
    Dim fs As New FileStream(filename, FileMode.Open, _
    Dim err_number As Integer = Err.Number

    On Error GoTo 0
    If err_number = 0 Then Return False
    If err_number = FILE_LOCKED Then Return True
End Function
Run the program and try clicking the button while you have the file test.txt open in Word and not.

There's still a big performance hit the first time you try to open a locked file. If you know of a better way to do this, please let me know. In particular, I'd like to know how to:

  • Get better performance
  • List all files open by processes
  • Find out which process has a particular file locked
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.