C# 检测文件是否被另一个进程(或实际上是同一个进程)锁定
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/424830/
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
Detecting whether a file is locked by another process (or indeed the same process)
提问by Hyman Hughes
This is how I do it at the moment. I try to open the file with the FileShare set to none. So I want exclusive accesss to the file. If I can't get that then its a good bet somebody else has the file locked.
这就是我目前的做法。我尝试在 FileShare 设置为 none 的情况下打开文件。所以我想要对文件的独占访问。如果我不能得到它,那么我打赌其他人已经锁定了文件。
There's got to be a better and faster way. Any ideas?
必须有更好更快的方法。有任何想法吗?
try
{
using (FileStream fs = File.Open(GetLockFilename(), FileMode.Open, FileAccess.ReadWrite, FileShare.None))
{
fs.Close();
}
// The file is not locked
}
catch (Exception)
{
// The file is locked
}
采纳答案by Sunny Milenov
There is no need first to check if the file is locked and then access it, as between the check and the access some other process may still get a lock on the file. So, what you do is correct, if you succeed, do your work with the file.
无需先检查文件是否被锁定然后再访问它,因为在检查和访问之间,某些其他进程可能仍会锁定文件。所以,你所做的是正确的,如果你成功了,就用这个文件做你的工作。
回答by Otávio Décio
No that I am aware of, there is no call to check if the file is in use - you have to try to open it and handle the exception as you are doing. Another problem is that it is hard to distinguish between in use and no access allowed.
不,我知道,没有调用来检查文件是否正在使用 - 您必须尝试打开它并在执行时处理异常。另一个问题是很难区分正在使用和不允许访问。
回答by BFree
The truth is, even if you do figure out a way to check if the file is "locked" by the time you get to the next line where you open the file, something else in the OS may try to get a hold of that file, and your code to open it will fail anyway. You'll have to put a try/catch there anyway. Therefore, I say no. There isn't really a better solution.
事实是,即使您确实找到了一种方法来检查文件是否在打开文件的下一行时被“锁定”,操作系统中的其他东西也可能会尝试获取该文件,并且您打开它的代码无论如何都会失败。无论如何,您必须在那里进行尝试/捕获。因此,我说不。真的没有更好的解决方案。
回答by Marcus Santodonato
To answer your question, it would be more efficient to write the following extension method for the FileInfo class:
要回答您的问题,为 FileInfo 类编写以下扩展方法会更有效:
public static bool IsLocked(this FileInfo f)
{
try
{
string fpath = f.FullName;
FileStream fs = File.OpenWrite(fpath);
fs.Close();
return false;
}
catch (Exception) { return true; }
}
Once you have created the method, you can do a quick check like this:
创建方法后,您可以像这样进行快速检查:
FileInfo fi = new FileInfo(@"C:67918.TIF");
if (!fi.IsLocked()) { //DO SOMETHING HERE; }