4

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, i.e. it has been opened (for reading or writing) with FileShare.Read or FileShare.Write access."

I tested this using the following code (ommitted using blocks and Close() for brevity):

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 e.g. for reading without creating a lock?

Grigory Zhadko
  • 1,484
  • 1
  • 19
  • 33
Klaus P.
  • 43
  • 8
  • I've edited the accepted answer to remove the confusing statement. I suspect the author copied it from another answer pointing out the issue with `FileAccess.ReadWrite` and read-only files. – Collin Dauphinee Jun 08 '21 at 23:41

1 Answers1

0

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. It is possible to open a file without any sort of mutual exclusion on POSIX-based systems. However, .NET was exclusive to Windows at the time of the quoted answer.

Collin Dauphinee
  • 13,664
  • 1
  • 40
  • 71