c#如何检测文件是否在另一个进程中打开

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17475889/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-10 09:35:25  来源:igfitidea点击:

c# how to detect if file is open in another process

c#filedetect

提问by Edward Ned Harvey

I have seen these questions, and I am not asking the same question:
Is there a way to check if a file is in use?
and
How to check if file is in use in c#?

我已经看到了这些问题,但我不是在问同样的问题:
有没有办法检查文件是否在使用中?
以及
如何检查文件是否在 c# 中使用?

I am asking the question, how to detect if file is open in another process. It's the same question those other guys asked, but the answers they got tell them to see if they can get exclusive lock on the file, in order to imply the file being open in another process. I do not wish to get exclusive lock on a file, because I don't want to potentially interfere with the operation of the other processes.

我在问一个问题,如何检测文件是否在另一个进程中打开。这与其他人问的问题相同,但他们得到的答案告诉他们,看看他们是否可以获得文件的排他锁,以暗示该文件正在另一个进程中打开。我不希望获得文件的排他锁,因为我不想潜在地干扰其他进程的操作。

Also, different OSes might behave differently - some OSes might support things like filesystem-level or block-level snapshots or shadow copies, which might allow you to get exclusive lock on a file, even ifsome other process has the file open for reading.

此外,不同的操作系统可能会有不同的行为 - 一些操作系统可能支持文件系统级或块级快照或卷影副本等内容,这可能允许您获得文件的排他锁,即使某些其他进程已打开文件以供读取。

One person in the other questions said you can test all the open file handles in the system. Is that the only way? And if so, how would one go about doing it in C#? I don't see any obvious native .Net class to browse all the open file handles in the system.

其他问题中的一个人说您可以测试系统中所有打开的文件句柄。这是唯一的方法吗?如果是这样,人们将如何在 C# 中做到这一点?我没有看到任何明显的本地 .Net 类来浏览系统中所有打开的文件句柄。

采纳答案by sudheer keesara