如何知道某个文件夹的文件是否正在被另一个进程使用?
我知道已经有数十个关于“另一个进程正在使用的文件”的问题。但它们都存在尝试读取文件或写入已被另一个进程使用的文件的问题。我只是想检查一个文件是否正在被另一个进程使用(此后没有 IO 操作)。 我在其他地方没有找到答案。 那么,在 C# 中如何知道某个文件或文件夹是否正在被另一个进程使用呢?
I know there are tens of questions already about "the file being used by another process". But they all have the problem of trying to read a file or write to a file that is already being used by another process. I just want to check to see if a file is being used by another process (no IO action after that).
I didn't find the answer elsewhere.
So, how can I know if a file or folder is being used by another process in C#?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
正如您在问题中所描述的,唯一的方法是首先尝试打开该文件以查看它是否被另一个进程使用。
您可以使用我之前实现的这个方法,其想法是如果文件存在,则尝试以打开写入方式打开该文件,因此如果失败,则该文件可能被另一个进程使用:
As you describe in the question the only way is to try to open the file first to see if it used by another process.
You can use this method I implemented sometime ago, the idea is if the file exists then try to open the file as open write, and so if failed then the file maybe is used by another process:
这篇文章可能会有所帮助:
如何检查文件锁定?
This post might help:
How to check for file lock?