Title: See if a file is locked in C#
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 the example to experiment with it and to see additional details.
|