C# – Using C# is it possible to test if a lock is held on a file


I use an offset into a file and the Filestream lock/unlock menthods to control read/write access. I am using the following code to test if a lock is currently held on the file

  fs.Lock( RESERVED_BYTE, 1 );
  fs.Unlock( RESERVED_BYTE, 1 );
  rc = 1;
  rc = 0; 

My goal is to eliminate the try/catch block. Is there some better way to see if the lock exists?

Note: This question is not about if the file exists. I already know it does. It is about synchronizing write access.

Best Solution

You can call the LockFile Windows API function through the P/Invoke layer directly. You would use the handle returned by the SafeFileHandle property on the FileStream.

Calling the API directly will allow you to check the return value for an error condition as opposed to resorting to catching an exception.

Noah asks if there is any overhead in making the call to the P/Invoke layer vs a try/catch.

The Lock file makes the same call through the P/Invoke layer and throws the exception if the call to LockFile returns 0. In your case, you aren't throwing an exception. In the event the file is locked, you will take less time because you aren't dealing with a stack unwind.

The actual P/Invoke setup is around seven instructions I believe (for comparison, COM interop is about 40), but that point is moot, since your call to LockFile is doing the same thing that the managed method does (use the P/Invoke layer).