如何以编程方式检测哪个程序捕获了我的文件
我的程序尝试将一些数据写入文本文件。但有时该文件只能由其他程序打开。
如何以编程方式检测哪个程序捕获了我的文件?我必须知道用户友好的程序名称(这是我的第二个问题:))。
My program tries to write some data to a text file. But sometimes this file can be opened by some other program exclusively.
How to detect programmatically what program caught my file? I have to know user-friendly program name (here is my second question :)) that did it.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您可以通过尝试打开文件时收到的 IOException 来检测它。这是多任务操作系统上不可避免的祸害,没有可靠的方法来实现 File.IsLocked() 方法。 Windows 没有相应的 API 函数。因为如果这样的函数返回 false,另一个进程可能会中断您的程序并锁定文件。当你拿回cpu时,你会发现文件无论如何都被锁定了。这就是所谓的线程竞赛。
因此,使用 FileStream 构造函数打开文件。如果您想从另一个进程正在写入的文件中读取数据,请传递 FileShare.ReadWrite。您必须允许读写共享,其他进程已经获得了写访问权限。捕获您可能收到的 IOException,您必须“稍后”重试。告诉用户这一点,她可能会知道如何帮助您。就像关闭另一个程序一样。
顺便说一句,Windows 没有提供任何方法来查明哪个其他进程锁定了该文件。有一些实用程序可以实现此目的,例如 SysInterals 的 Handle 实用程序。它使用动态安装的设备驱动程序探索未记录的内部内核结构。没有什么是你想自己解决的。
You detect it by the IOException you get when you try to open the file. This is a necessary evil on a multi-tasking operating system, there is no reliable way to implement a File.IsLocked() method. Windows doesn't have an API function for it. Because if such a function returns false, another process could interrupt your program and lock the file. When you get the cpu back, you'll find that the file is locked anyway. That's called a threading race.
So open the file with, say, the FileStream constructor. Pass FileShare.ReadWrite if you want to read from a file that's being written by another process. You have to allow ReadWrite sharing, the other process already gained the write access right. Catch the IOException you may get, you'll have to try again 'later'. Tell the user about it, she'll probably know what to do to help you. Like closing another program.
Btw, Windows does not provide any way to find out what other process has the file locked. There are utilities for that, like SysInterals' Handle utility. It grovels through undocumented internal kernel structures with a device driver that's dynamically installed. Nothing you'd want to tackle yourself.