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

Horas picture Horas · Nov 5, 2008 · Viewed 95.9k times · Source

Basically, I would like to check if I have rights to open the file before I actually try to open it; I do not want to use a try/catch for this check unless I have to. Is there a file access property I can check before hand?

Answer

Joel Coehoorn picture Joel Coehoorn · Nov 5, 2008

I have done this countless times in the past, and nearly every time I've done it 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. A change 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 that you still have to be able 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 for the permissions of the file in advance. Exception handling code provides all of the functionality of existence or permissions checks. Additionally, while exception handlers like this are known to be slow, it's important to remember that disk i/o is even slower... a lot slower... and calling the .Exists() function or checking permissions will force an additional trip out the file system.

In summary, 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, and it can introduce subtle bugs into your code. There is just no upside at all to doing the initial check. Instead, the correct thing here is to just try to open the file and put your effort into a good exception handler if it fails. The same is true even if you're just checking whether or not the file exists. This reasoning applies to any volatile resource.