See if a file is locked in C#

[locked]

Some applications lock files so you cannot write, read, delete, or otherwise mess with them. For example, when you open a file in Microsoft Word, it locks the file so you cannot delete it or open it for writing with another application.

The following FileIsLocked method returns true if a file is locked for a given kind of access. For example, pass this routine the access value FileAccess.Write if you want to learn whether the file is locked to prevent you from writing into it.

// Return true if the file is locked for the indicated access.
private bool FileIsLocked(string filename, FileAccess file_access)
{
    // Try to open the file with the indicated access.
    try
    {
        FileStream fs =
            new FileStream(filename, FileMode.Open, file_access);
        fs.Close();
        return false;
    }
    catch (IOException)
    {
        return true;
    }
    catch (Exception)
    {
        throw;
    }
}

The code simply tries to open the file for the given access method and sees whether that causes an error. It uses a try-catch block to handle any error that might occur. If the error is an IOException, then the method assumes the file is locked.

Note, however, that there may be other reasons the method could not access the file. For example, if the file’s path is on a nonexistent disk drive, the code will receive an IOException.

To avoid this kind of false positive, you might want to first check whether the file exists, at least if you’re checking read permissions. If you’re checking for a write lock, you may not need the file to exist if you’re going to overwrite the file. I decided to leave this issue out of the example to keep things simpler.


Download Example   Follow me on Twitter   RSS feed   Donate




This entry was posted in files, system and tagged , , , , , , , , , , , , , , . Bookmark the permalink.

3 Responses to See if a file is locked in C#

  1. Adrian says:

    It would be really nice if the program could tell which other program or programs have locked the file, so we have a starting point on how to unlock it.

    PS. Thanks for writing all these nice little articles. I enjoy reading and learning from them.

Leave a Reply

Your email address will not be published. Required fields are marked *