Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to best wait for a filelock to release

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.

like image 547
Tjelle Avatar asked Mar 27 '09 15:03

Tjelle


2 Answers

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.");
    }
}
like image 98
Darin Dimitrov Avatar answered Oct 11 '22 15:10

Darin Dimitrov


There's a useful discussion on google groups which you really should read. One of the options is close to darin's; however, to guarantee you get the right win32 error, you really should call the win32 OpenFile() API yourself (otherwise, you really don't know which error you are retrieving).

Another is to parse the error message: that will fail if your application is run on another language version.

A third option is to hack inside the exception class with reflection to fish out the actual HRESULT.

None of the alternatives are really that attractive: the IOException hierarchy would benefit from a few more subclasses IMHO.

like image 20
Pontus Gagge Avatar answered Oct 11 '22 15:10

Pontus Gagge