how can you easily check if access is denied for a file in .NET?

I have done this countless times in the past, and nearly every time I was wrong to even make the attempt.

File permissions (even file existence) are volatile — they can change at any time. Thanks to Murphy’s Law this especially includes the brief period between when you check the file and when you try to open it. There are other reasons this can fail, too, such as locking or network availability and path resolution. An errant result is even more likely if you’re in an area where you know you need to check first. Yet strangely enough it will never happen in your testing or development environments, which tend to be fairly static. This makes the problem difficult to track down later and makes it easy for this kind of bug to make it into production.

What this means is you must still be ready to handle the exception if file permissions or existence are bad, in spite of your check. Exception handling code is required, whether or not you check the file in advance, and good exception handler can provide all of the functionality of existence or permissions checks.

But isn’t exception handling slow? I’m glad you asked. Yes, yes it is. In fact, unwinding the stack to handle an exception is up there with the slowest stuff you can do inside a single computer. However, it’s important to remember that disk I/O is even slower — a lot slower — and calling the .Exists() function or checking permissions will always force an additional I/O operation on the file system.

Therefore, we see an initial check before trying to open the file is both redundant and wasteful. There is no additional benefit over exception handling. It will actually hurt, not help, your performance. It adds cost in terms of more code that must be maintained. Finally, it can introduce subtle bugs. There is just no upside at all to doing the initial check.

Instead, the correct thing here is immediately trying to open the file, with no initial check, and putting your effort into a good exception handler if it fails. The same is true whether you’re checking permissions, locking, or even just whether or not the file exists.

In summary: the choice is paying the extra cost for file check every time with more code, or paying the smaller-but-still-bad cost for exception handling only some of the time and with less code.

Leave a Comment