Check if a file is locked

One notable feature that is missing from the IO section of the .NET base class library is a way to check if a file is locked. When opening a file the OpenFile et al API methods does actually provide the information, we just have to dig a little to discover it.

static bool IsFileLocked(string filename)  
{
    bool locked = false;
    try
    {
        File.Open(filename, FileMode.Open, FileAccess.ReadWrite, FileShare.None).Dispose();
    }
    catch (IOException e)
    {
        const int ERROR_SHARING_VIOLATION = 0x20;
        const int ERROR_LOCK_VIOLATION = 0x21;
        int errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);
        locked = errorCode == ERROR_SHARING_VIOLATION
               || errorCode == ERROR_LOCK_VIOLATION;
        if (!locked)
            throw;                
    }
    return locked;
}
Google
m@kli.dk @klinkby RSS feed  GitHub