File locked by which process?

久未见 提交于 2019-12-22 03:48:06

问题


Is there a way in .Net to find out exactly which process has locked a file?

EDIT: I'm doing this because I want to let my user know that they can't modify/open the file, because at the moment, another program they're using (such as Excel) has it open. Hopefully, this helps.


回答1:


The short answer to this is no.

However, the long answer is that there are various API calls and WMI methods that you can use to find this information out, but don't expect it to be quick and simple.

If you want to use API calls, take a look at the NtQuerySystemInformation function with the SYSTEM_PROCESS_INFORMATION parameter. This is one of those lovely "undocumented" methods that comes with the wonderful disclaimer:

NtQuerySystemInformation may be altered or unavailable in future versions of Windows. Applications should use the alternate functions listed in this topic.

So I would suggest avoiding that in favour of using WMI.

You can use the WMI Win32_Process class to enumerate all processes currently running on the machine, and then enumerate all handles each process is holding until you find the file you are looking for. Unfortunatly there is no simple way to go "hey, which process is locking this file", it only works the other way round you have to search down the process list until you find the one that is locking the file you are interested in.

I'd recommend a nice little article on CodeProject titled How To: (Almost) Everything In WMI via C# Part 2: Processes. (Part 1 is also a good read if you like that kind of thing)




回答2:


Well... it's not exactly a .NET way of doing it... but assuming you just want to find out using an easy utility, check out Handle from SysInternals.




回答3:


Looks like somebody has figured this one out (and you may learn some French as well :) )

http://www.axcis.com.au/bb/viewtopic.php?p=505



来源:https://stackoverflow.com/questions/2479733/file-locked-by-which-process

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!