I have to recycle IIS (version 7.5) application pool programatically using c#. When I try to get ApplicationPoolCollection using "ServerManager" class UnauthorizedAccessException raised. I guess I have to use impersonation. But I don't know to use impersonation. And is there anyway to use impersonation with attribute instead of web.config?
1 Answers
To perform any administrative operations in IIS such as recycling application pools, starting and stopping sites, creating websites and so on, you need to run as administrator.
If you want to programmatically impersonate a user then you need to use the WindowsIdentity.Impersonate
method.
There's a reasonably good snippet of sample code there to get you started.
Of course all the usual caveats apply here when it comes to storing credentials for highly privileged users in your web.config
file (or hard coded).
Also if you're trying to debug code that accesses IIS programmatically using the managed ServerManager
API then make sure you start Visual Studio by doing "Run As Administrator". You need to do this even if your own Windows account is a member of the Administrators group.

- 118,037
- 53
- 300
- 385