Is there any solution to extract the name of the user who locks/has a specific file open?
With a basic try-catch, I can check if the file is editable or not, but I would need to notify the client who locks the file so they can act immediately.
Please refer below vb.net code, you can invoke it in Uipath.
Private Sub Workbook_Open()
Dim Folder As String
Dim FName As String
Dim strFilename As String
Folder = "C:"
FName = âdata.xlsâ
If Not FileLocked(Folder & FName) Then
MsgBox âFile " & Folder & FName & " is not openâ
Else
MsgBox "The file is locked by " & GetFileOwner(Folder, FName) & â.â
End If
End Sub
Function GetFileOwner(fileDir As String, fileName As String) As String
'On Error Resume Next
Dim secUtil As Object
Dim secDesc As Object
Set secUtil = CreateObject(âADsSecurityUtilityâ)
Set secDesc = secUtil.GetSecurityDescriptor(fileDir & fileName, 1, 1)
GetFileOwner = secDesc.Owner
End Function
Function FileLocked(strFilename As String) As Boolean
On Error Resume Next
â If the file is already opened by another process,
â and the specified type of access is not allowed,
â the Open operation fails and an error occurs.
Open strFilename For Binary Access Read Write Lock Read Write As #1
Close #1
â If an error occurs, the document is currently open.
If Err.Number <> 0 Then
â Display the error number and description.
'MsgBox âError #â & Str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function
I am having a file which is in the shared folder and can be accessible by the multiple users.
When the bot is executing and it wants to access that file it will through an exception stating âThe file is being used by another user.ââ
So, here in the catch block, I want to know the name of the person who is using that file. Can you help me on this?
If you are able to run a macro on that workbook/sheet, you can use the âinvoke macroâ to run the macro. This requires you to store the macro as a .vbs file (with slight alterations), or to store the macro in the referenced workbook (requiring extension to be .xlsm or .xlsb), or stored in the personal workbook (and thus requiring each robot running the code to have the same macro in their personal workbook).
If it isnât excel, then the VBA solution will not work. Iâd try the vb.net code referenced in the link above. I havenât ever done this myself so I canât give much more help than that, sorry!
It looks like that is getting the âownerâ property of the file, which is not going to be the current user locking the file
You can also see the original creator using the same WindowsAPICodePack.Shell library and check the System.Author property (instead of the .LastAuthor property). See documentation here: System (Windows) | Microsoft Learn