This question already has an answer here:
- Is there a way to check if a file is in use? 18 answers
original title: "c# - How to check for file lock?"
This question already has an answer here:
この質問にはすでに回答があります:ファイルが使用中かどうかを確認する方法はありますか? 18答え...
これは翻訳後の要約です。完全な翻訳を表示する必要がある場合は、「翻訳」アイコンをクリックしてください。
No, unfortunately, and if you think about it, that information would be worthless anyway since the file could become locked the very next second (read: short timespan).
Why specifically do you need to know if the file is locked anyway? Knowing that might give us some other way of giving you good advice.
If your code would look like this:
Then between the two lines, another process could easily lock the file, giving you the same problem you were trying to avoid to begin with: exceptions.
When I faced with a similar problem, I finished with the following code:
The other answers rely on old information. This one provides a better solution.
Long ago it was impossible to reliably get the list of processes locking a file because Windows simply did not track that information. To support the Restart Manager API, that information is now tracked. The Restart Manager API is available beginning with Windows Vista and Windows Server 2008 (Restart Manager: Run-time Requirements).
I put together code that takes the path of a file and returns a
List<Process>
of all processes that are locking that file.UPDATE
Here is another discussion with sample code on how to use the Restart Manager API.
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.
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 could call LockFile via interop on the region of file you are interested in. This will not throw an exception, if it succeeds you will have a lock on that portion of the file (which is held by your process), that lock will be held until you call UnlockFile or your process dies.
A variation of DixonD's excellent answer (above).
Usage:
Here's a variation of DixonD's code that adds number of seconds to wait for file to unlock, and try again:
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.
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.
Same thing but in Powershell
What I ended up doing is: