PDA

View Full Version : Check for open file.



sconly
11-21-2011, 08:03 AM
I have an Excel solution and i want it to check if a certain text (.txt) file is open before it does anything else.

How can i go about performing this check?

It's going to be used on machines running either Excel 2003 or Excel 2010.

Thanks.

mancubus
11-21-2011, 09:04 AM
hi.

below procedure tests if notepad.exe is running


Public Sub showProcesses()
'http://www.xtremevbtalk.com/showthread.php?t=150016

Dim W As Object
Dim sQuery As String
Dim processes As Object
Dim process As Object

Set W = GetObject("winmgmts:")
sQuery = "SELECT * FROM win32_process"
Set processes = W.execquery(sQuery)

For Each process In processes
If process.Name Like "notepad.exe" Then 'you can also get the process.Handle
MsgBox "Notepad is open"
End If
Next

Set W = Nothing
Set processes = Nothing
Set process = Nothing

End Sub



and see the attached file here:
http://blog.didierstevens.com/2011/02/03/taskmanager-xls/

sconly
11-21-2011, 09:27 AM
Thanks for the reply.

This looks like its just checking if notepad is open, not the actual text file.

What if they're not using notepad as the text editor/viewer?

Also, they might have notepad open but not viewing/editing the text file.

mancubus
11-21-2011, 09:29 AM
you're wellcome.

found it. modify below proc to suit your needs.


Sub list_app()
'http://social.msdn.microsoft.com/Forums/en/isvvba/thread/93674f48-299e-4880-b77f-5f7bc66b2e75

Dim flag As Boolean
Dim strComputer As String

strComputer = "."

Set objWMIService = GetObject("winmgmts:\\" & strComputer & "\root\CIMV2")
Set colItems = objWMIService.ExecQuery("SELECT * FROM Win32_Process", , 48)

flag = False
For Each objItem In colItems
If InStr(UCase(objItem.CommandLine), UCase("your_file_name_here.txt")) > 0 Then
flag = True
Exit For
End If
Next
If flag = True Then
MsgBox "Open"
Else
MsgBox "Not Open"
End If

End Sub

sconly
11-21-2011, 09:56 AM
Thanks for that but, my apologies, I haven't explained it very well.

The file is located in a shared folder on the network and what I'm actually trying to do is to check if another user has the file open whilst other users are trying to access it.

Can the above function still be used given my scenario?

Thanks!

...........and sorry!!

mancubus
11-21-2011, 11:27 AM
not knowing too much, i don't think so. it seems pc specific procedure.

to test, make someone else open the file then run the code.


_________
i opened a sample file in one pc with my user_id, and was able to delete the same file in another pc without being warned even the file is open.