Search code examples
c#.netiofilelock

How to check for file lock?


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.


Solution

  • 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:

    if not locked then
        open and update file
    

    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.