C#C
C#3y ago
6 replies
Nacho Man Randy Cabbage

How to check if a file is locked by another process and keep checking for specified amount of time?

I am trying to create a simple way for apps to check if a file is locked by another process before locking it themselves and reading/writing to it.

what is the simplest way to achieve this? Some nice-to-haves:
- See the name of the process that is locking it
- See how long the file has been locked for (is this possible?)
- Specify an amount of time/number of tries to check the lock


I've seen mentions of creating a separate file that can act as a "lock" file, i.e. if it exists it means the original file is locked, and having the process doing the locking delete the lock file when it's finished. This seems overly complicated. In my head it should be as simple as just having a using statement on a filestream with FileShare set to None. If it doesn't throw an exception, then it is not locked. But I guess if I want to see how long a file has been locked for then I might need to write that information somewhere (like the "lock" file).

Any tips would be greatly appreciated
Was this page helpful?