This question already has an answer here:
- Is there a way to check if a file is in use? 16 answers
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
.
Same thing but in Powershell
However, this way, you would know that the problem is temporary, and to retry later. (E.g., you could write a thread that, if encountering a lock while trying to write, keeps retrying until the lock is gone.)
The IOException, on the other hand, is not by itself specific enough that locking is the cause of the IO failure. There could be reasons that aren't temporary.
Instead of using interop you can use the .NET FileStream class methods Lock and Unlock:
FileStream.Lock http://msdn.microsoft.com/en-us/library/system.io.filestream.lock.aspx
FileStream.Unlock http://msdn.microsoft.com/en-us/library/system.io.filestream.unlock.aspx
You can see if the file is locked by trying to read or lock it yourself first.
Please see my answer here for more information.
When I faced with a similar problem, I finished with the following code:
You can also check if any process is using this file and show a list of programs you must close to continue like an installer does.