开发者

C# How to to tell what process is using a file?

开发者 https://www.devze.com 2022-12-24 07:39 出处:网络
I am getting a p开发者_Go百科retty common, \"The process cannot access the file because it is being used by another process.\"

I am getting a p开发者_Go百科retty common, "The process cannot access the file because it is being used by another process."

Now I am nearly certain that the only process accessing this file is from code that I have written and I've been careful to use a using statement around accessing it.

But to be 100% sure, is there anyway to check this programatically when this error occurs?


There is also a small tool handle.exe in Sysinternals Suite that does exactly what you need. Use it from the command line:

handle.exe -a <filename>

Of course under Vista and Windows 7 this tool must be run elevated.


e.g. oh.exe from the Resource Kit and Process Explorer from sysInternals both show who is using what

Both of them use techniques not available in C#.


Windows Vista adds a new function, GetRunningObjectTable which you can use to detect which program has a file open. This only works in Vista+, and it only works when the application that has the file open actually implements supports for IFileIsInUse (e.g. Office supports it, but most 3rd-party apps probably don't).

Other than that, the usual way this is implemented is by opening each process, enumerating the file handles they have open and searching for the filename in question. This is pretty low-level, and would require quite a bit of P/Invoke to implement in C#, but it's not impossible.

It's usually easy enough just to open up Process Explorer and let it do the search.

0

精彩评论

暂无评论...
验证码 换一张
取 消