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?