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.




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.
This used to be impossible but now you can do it with the Restart Manager. See this MSDN post:
How to know the process locking a file
See this C# Helper post:
See what processes have a file locked in C#
How to delete all files in a folder but skip files in use?
I think you could loop through the files, use the method described here to see if it is locked, and delete the files that are not locked.
Use the following example if you want to move the files into the wastebasket instead of permanently deleting them:
Manage the recycle bin (wastebasket) in C#>a
Also note that not all applications lock files correctly. For example, MS Paint does not lock files when you open them. That means, for example, that you can use File Explorer to delete a picture file while Paint is working on it. Your program can probably delete the file, too.