It is often a requirement in your web application to run with impersonation on. This ensures that the users credentials are directly related to whoever is logged in. However, sometimes you need access to a local file system in which that user may not have access too. What you can do is give access to the App Pool Identity associated with the web application, and then simply turn impersonation off programmatically while you access that directory. Of course once you are finished you need to turn it back on.
Check it out:
Although, technically, you are not “disabling” impersonation here, but rather just changing the impersonated context to that of the account used by the App pool… But that works… same effect, I suppose.
You should put WindowsImpersonationContext ctx = WindowsIdentity.Impersonate(IntPtr.Zero); inside the try – that way you are sure that once impersonation has completed the finally will be called.