简体   繁体   English

检查文件是否正在使用 - 附加问题

[英]Check if file is in use - additional question

I'm trying to find an alternative to using the Restart Manager for checking if a file is locked.我正在尝试找到使用重新启动管理器检查文件是否被锁定的替代方法。 I found this accepted answer to the same question.我找到了对同一问题的公认答案 However, the accepted answer contains the following comment that I do not understand: "this solution will not work if the file doesn't have a Write or Read lock on it, ie it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access."但是,接受的答案包含以下我不理解的评论:“如果文件没有写入或读取锁定,则此解决方案将不起作用,即已使用 FileShare 打开(用于读取或写入)。读取或 FileShare.Write 访问权限。”

I tested this using the following code (ommitted using blocks and Close() for brevity):我使用以下代码对此进行了测试(为简洁起见,使用块和 Close() 省略了):

static void Main(string[] args)
{
    const string fileName = "test.txt";

    // This should open the file as described, shouldn't it?
    var fi1 = new FileInfo(fileName);
    // Test with FileShare.Read / FileShare.Write / FileShare.ReadWrite gives the same result
    var fs1 = fi1.Open(FileMode.OpenOrCreate, FileAccess.Write, FileShare.Write);

    var fi2 = new FileInfo(fileName);
    Console.WriteLine($"Is file locked? {IsFileLocked(fi2)}");
    // Displays always: "Is file locked? True" 

    Console.ReadLine();
}

This displays always "Is file locked? True" whereas it should display "False" according to the comment.这始终显示“文件被锁定吗?真”,而根据评论它应该显示“假”。

I tested also the code of this answer which has a similar comment with no luck.我还测试了这个答案的代码,它有类似的评论,但没有运气。 Tested also with two seperate processes - as expected no difference.还使用两个单独的过程进行了测试 - 正如预期的那样没有区别。

Looking at the docs , my test results seem resonably - but I'm puzzled by the above mentioned comments.查看文档,我的测试结果似乎合理 - 但我对上述评论感到困惑。

How else would I open a file eg for reading without creating a lock?我如何在不创建锁的情况下打开文件,例如进行阅读?

The part of the answer that you quoted is incorrect.您引用的部分答案不正确。 The mechanism that prevents you from opening an already open file is the share mode, not the desired access type.阻止您打开已打开文件的机制是共享模式,而不是所需的访问类型。

When you attempt to open a file that is already in use, the share mode requested is compared against the share mode that the file was opened with.当您尝试打开已在使用的文件时,系统会将请求的共享模式与打开文件时使用的共享模式进行比较。 If they don't match up, your call fails.如果它们不匹配,您的呼叫将失败。

EDIT: Just to cover all of my bases, the above only holds true on Windows.编辑:只是为了涵盖我的所有基础,以上仅适用于 Windows。 It is possible to open a file without any sort of mutual exclusion on POSIX-based systems.在基于 POSIX 的系统上,可以在没有任何互斥的情况下打开文件。 However, .NET was exclusive to Windows at the time of the quoted answer.但是,在引用答案时,.NET 是 Windows 独有的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM