Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I programatically determine which application is locking a file? [duplicate]

Tags:

c#

.net

windows

Possible Duplicate:
How do I find out which process is locking a file using .NET?

I want to copy a file but it is locked by another application, so a FileInUseException is thrown. I would like to tell the user which application is locking the file I'm trying to copy. Is there a way in the .NET Framework to do this? Without this knowledge, I'm resorting to telling the users to use the Unlocker application.

like image 667
Michael Hedgpeth Avatar asked Jan 27 '11 13:01

Michael Hedgpeth


2 Answers

Keeping in mind the caveats Ed pointed out, on Vista an later, you can use the Restart Manager APIs to accomplish this (even if your app isn't an installer).

You create a new session, register the file of interest, then call RmGetList to get the list of applications or services that have a handle on the file. You should be able to even initiate a restart of those applications if they're Restart Manager-aware without involving the user.

Clearly, the Restart Manager is a Win32 API, but you should be able to P/Invoke into it. This article: http://msdn.microsoft.com/en-us/magazine/cc163450.aspx has the needed P/Invoke signatures as well as examples of use in this manner.

like image 89
Eugene Talagrand Avatar answered Oct 16 '22 07:10

Eugene Talagrand


You could try the code provided in this question over here, or look at other suggestions here.

The general approach is to enumerate the handles of all processes, get the file paths of those handles, and compare against the file you're interested in.

But a problem with this approach is that even if you can determine that the file is locked and which application has the file lock then you will still have to cope with race conditions, for example...

one millisecond later

  • the file is not locked
  • the application that did hold the lock is now not

then two milliseconds later

  • the file is locked (again)
  • a different application has the lock

then three milliseconds later

  • the file is still locked
  • yet another app has the lock

...etc

One suggestion is to attempt to get the file handle in your app, and catch the exception when you can't.

 try
 {
    using (Stream stream = new FileStream("MyFilename.txt"))
   {
   }
 } catch {
   //check here why it failed and ask user to retry if the file is in use.
}

Of course this won't help identify the culprit(s) but at least you have a safer way of attempting to access the file.

like image 35
Ed Guiness Avatar answered Oct 16 '22 06:10

Ed Guiness