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.
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.
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.
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.
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.
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.