I think one of the first steps in troubleshooting the dreaded “permission denied” exception in a server application is to ask the question: To whom did the system deny permission?
The knee jerk reaction to this exception is to wander off into the security dialog boxes and start giving the Everyone group permissions. Just to test it, you see. Really. When this doesn’t work, the next step is to start running everything as SYSTEM. Just as a test! Before long, you have an unholy mess of ACL modifications and config file tweaks to undo.
Just like a good murder mystery sometimes this question has a surprising answer. You might be assuming the answer is the NETWORK SERVICE or ASPNET account, or the impersonated user. As a server request makes its way across threads and through pipelines, to unmanaged code and back and hopping from machine to machine, there are a slew of reasons why the security context might not be who you think it is at that point in time when the exception occurs.
Consider these scenarios:
All three scenarios can result in a security context you didn’t expect trying to get to a protected resource. (Yep, I've hit them all).
I think the first step is to find out whodunit. I’ve generally answered this question by enabling security auditing at the right spots. Keith Brown discusses how to enable auditing, and how to audit access to files in his book: a .net developer’s guide to Windows security. As Keith points out, auditing can also help you track down other silly problems that cause exceptions and make you remove hair from your scalp, like expired passwords and locked out accounts.