how to best wait for a filelock to release

Tjelle picture Tjelle · Mar 27, 2009 · Viewed 7.3k times · Source

I have an application where i sometimes need to read from file being written to and as a result being locked. As I have understood from other questions i should catch the IOException and retry until i can read.

But my question is how do i know for certain that the file is locked and that it is not another IOExcetpion that occurs.

Answer

Darin Dimitrov picture Darin Dimitrov · Mar 27, 2009

When you open a file for reading in .NET it will at some point try to create a file handle using the CreateFile API function which sets the error code which can be used to see why it failed:

const int ERROR_SHARING_VIOLATION = 32;
try
{
    using (var stream = new FileStream("test.dat", FileMode.Open, FileAccess.Read, FileShare.Read))
    {
    }
}
catch (IOException ex)
{
    if (Marshal.GetLastWin32Error() == ERROR_SHARING_VIOLATION)
    {
        Console.WriteLine("The process cannot access the file because it is being used by another process.");
    }
}