文件被哪个进程锁定?

发布于 2024-08-25 10:13:30 字数 132 浏览 7 评论 0原文

.Net 中有没有办法准确找出哪个进程锁定了文件?

编辑:我这样做是因为我想让我的用户知道他们无法修改/打开该文件,因为目前他们正在使用的另一个程序(例如 Excel)已它打开了。希望这会有所帮助。

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

小梨窩很甜 2024-09-01 10:13:30

对此的简短回答是否定的。

然而,长的答案是,您可以使用各种 API 调用和 WMI 方法来查找此信息,但不要指望它会快速而简单。

如果您想使用 API 调用,请查看 NtQuerySystemInformation 函数,带有 SYSTEM_PROCESS_INFORMATION 参数。这是那些可爱的“无证”方法之一,附带了精彩的免责声明:

NtQuerySystemInformation 可能是
将来更改或不可用
Windows 版本。应用领域
应该使用替代功能
列在本主题中。

所以我建议避免这种情况,转而使用 WMI。

您可以使用 WMI Win32_Process 类来枚举当前在计算机上运行的所有进程,然后枚举每个进程持有的所有句柄,直到找到您要查找的文件。 ,没有简单的方法可以“嘿,哪个进程正在锁定这个文件”,它只能以相反的方式工作,您必须向下搜索进程列表,直到找到锁定您感兴趣的文件的进程。

不幸的是 推荐 CodeProject 上一篇不错的小文章,标题为 如何:(几乎)WMI 中的所有内容,通过C# 第 2 部分:进程。 (如果您喜欢这类内容,第 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)

毁虫ゝ 2024-09-01 10:13:30

嗯...这不完全是 .NET 的实现方法...但是假设您只是想使用一个简单的实用程序来了解情况,请查看 来自 SysInternals 的句柄

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.

追我者格杀勿论 2024-09-01 10:13:30

看起来有人已经解决了这个问题(您也可以学习一些法语:))

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

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文