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.
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.
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
then two milliseconds later
then three milliseconds later
...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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With