How to check for file lock?

ricree picture ricree · Aug 4, 2008 · Viewed 199.7k times · Source

Is there any way to check whether a file is locked without using a try/catch block?

Right now, the only way I know of is to just open the file and catch any System.IO.IOException.

Answer

DixonD picture DixonD · Jul 8, 2010

When I faced with a similar problem, I finished with the following code:

public bool IsFileLocked(string filePath)
{
    try
    {
        using (File.Open(filePath, FileMode.Open)){}
    }
    catch (IOException e)
    {
        var errorCode = Marshal.GetHRForException(e) & ((1 << 16) - 1);

        return errorCode == 32 || errorCode == 33;
    }

    return false;
}