How can I determine if a file is locked using VBS?
Asked Answered
E

3

8

I am writing a VB Script to update some files on the network. Before beginning, I want to know if any of the files are locked. I'd like to do this before I actually do any updates.

I am aware that I can handle the error if the file is locked when I try to replace it, but I really want to know if any files are locked before I start updating any files.

Is there any way to see that a file is locked using VBS (apart from trying to replace it)?

Ectomorph answered 6/9, 2012 at 12:59 Comment(0)
V
15

This function determines whether a file of interest can be accessed in 'write' mode. This is not exactly the same as determining whether a file is locked by a process. Still, you may find that it works for your situation. (At least until something better comes along.)

This function will indicate that 'write' access is not possible when a file is locked by another process. However, it cannot distinguish that condition from other conditions that prevent 'write' access. For instance, 'write' access is also not possible if a file has its read-only bit set or possesses restrictive NTFS permissions. All of these conditions will result in 'permission denied' when a 'write' access attempt is made.

Also note that if a file is locked by another process, the answer returned by this function is reliable only at the moment the function is executed. So, concurrency problems are possible.

An exception is thrown if any of these conditions are found: 'file not found', 'path not found', or 'illegal file name' ('bad file name or number').

Function IsWriteAccessible(sFilePath)
    ' Strategy: Attempt to open the specified file in 'append' mode.
    ' Does not appear to change the 'modified' date on the file.
    ' Works with binary files as well as text files.

    ' Only 'ForAppending' is needed here. Define these constants
    ' outside of this function if you need them elsewhere in
    ' your source file.
    Const ForReading = 1, ForWriting = 2, ForAppending = 8

    IsWriteAccessible = False

    Dim oFso : Set oFso = CreateObject("Scripting.FileSystemObject")

    On Error Resume Next

    Dim nErr : nErr = 0
    Dim sDesc : sDesc = ""
    Dim oFile : Set oFile = oFso.OpenTextFile(sFilePath, ForAppending)
    If Err.Number = 0 Then
        oFile.Close
        If Err Then
            nErr = Err.Number
            sDesc = Err.Description
        Else
            IsWriteAccessible = True
        End if
    Else
        Select Case Err.Number
            Case 70
                ' Permission denied because:
                ' - file is open by another process
                ' - read-only bit is set on file, *or*
                ' - NTFS Access Control List settings (ACLs) on file
                '   prevents access

            Case Else
                ' 52 - Bad file name or number
                ' 53 - File not found
                ' 76 - Path not found

                nErr = Err.Number
                sDesc = Err.Description
        End Select
    End If

    ' The following two statements are superfluous. The VB6 garbage
    ' collector will free 'oFile' and 'oFso' when this function completes
    ' and they go out of scope. See Eric Lippert's article for more:
    '   http://blogs.msdn.com/b/ericlippert/archive/2004/04/28/when-are-you-required-to-set-objects-to-nothing.aspx

    'Set oFile = Nothing
    'Set oFso = Nothing

    On Error GoTo 0

    If nErr Then
        Err.Raise nErr, , sDesc
    End If
End Function
Vermiculate answered 7/9, 2012 at 1:52 Comment(3)
Darin notes (in other answer) that this module should include: Const ForReading = 1, ForWriting = 2, ForAppending = 8Splenectomy
@Splenectomy - Thank you for bringing this omission to my attention. I have updated the code accordingly. Also note my comment preceding setting oFile and oFso to Nothing at the end of the function.Vermiculate
worked for me. thanks. just added few lines to check if the file exist: IsWriteAccessible = False Dim oFso: Set oFso = CreateObject("Scripting.FileSystemObject") If oFso.FileExists(sFilePath) = False Then IsWriteAccessible = True Exit Function End IfSymbology
O
3

The script below tries to write to a file for 30 seconds and gives up after that. I needed this when all our users had to click on a script. Chances are that multiple users try to write at the same time. OpenCSV() tries to open the file 30 times with a delay of 1 second in between.

  Const ForAppending = 8

  currentDate = Year(Now) & "-" & Month(Now) & "-" & Day(Now) & " " & Hour(Now) & ":" & Minute(Now) & ":" & Second(Now)
  filepath = "\\network\path\file.csv"
  Set oCSV = OpenCSV( filepath ) 
  oCSV.WriteLine( currentDate )
  oCSV.Close

  Function OpenCSV( path )
    Set oFS = CreateObject( "Scripting.FileSystemObject" )
    For i = 0 To 30
      On Error Resume Next
      Set oFile = oFS.OpenTextFile( path, ForAppending, True )
      If Not Err.Number = 70 Then
        Set OpenCSV = oFile
        Exit For
      End If
      On Error Goto 0
      Wscript.Sleep 1000
    Next
    Set oFS = Nothing
    Set oFile = Nothing
    If Err.Number = 70 Then
      MsgBox "File " & filepath & " is locked and timeout was exceeded.", vbCritical
      WScript.Quit
    End If
  End Function
Overarm answered 20/11, 2013 at 11:12 Comment(0)
B
1

Or, more simply:

Assuming you already have a variable in your VBS named FileName, which contains the full filepath you want to test:

Dim oFso, oFile
Set oFso = CreateObject("Scripting.FileSystemObject")
Set oFile = oFso.OpenTextFile(FileName, 8, True)
If Err.Number = 0 Then oFile.Close

Line 3 tries to open the file you want to test with append permissions enabled. e.g. it attempts to open the file with a write lock.

If opening the file with a write lock generates an error, then your VBS will error on the third line and not continue. At that point your error handling from wherever you called the VBS should kick in. The error message will be "Permission Denied" if you couldn't get a write lock.

If opening the file with a lock doesn't result in an error, then line 4 closes it again. You can now open the file or do whatever you want with it, confident that it doesn't have a write lock on it.

Bluefarb answered 2/3, 2021 at 14:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.