|
|
Title | See if a file is locked in Visual Basic 6 |
Description | This example shows how to see if a file is locked in Visual Basic 6. |
Keywords | file locked, file, locked |
Categories | Files 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 (reading or writing). For example, pass this routine the True 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. It then tries to open the file for reading or writing. If there is no error, the function returns False. If there is a permission 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, _
Optional ByVal for_write As Boolean = True) As Boolean
Const PERMISSION_DENIED As Integer = 70
Dim fnum As Integer
Dim err_number As Integer
On Error Resume Next
fnum = FreeFile
If for_write Then
Open filename For Append As #fnum
err_number = Err.Number
Else
Open filename For Input As #fnum
err_number = Err.Number
End If
Close #fnum
On Error GoTo 0
If err_number = 0 Then
FileIsLocked = False
ElseIf err_number = PERMISSION_DENIED Then
FileIsLocked = True
Else
Err.Raise err_number
End If
End Function
|
|
Run the program and try clicking the button while you have the file test.txt open in Word and not.
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
|
|
|
|
|
|