Run Code as a different user

Impersonation requires calling some native APIs (namely, LogonUser) so it's probably not worth posting 3 pages of wrapper code. This page has a complete working sample: http://platinumdogs.wordpress.com/2008/10/30/net-c-impersonation-with-network-credentials/

Note that impersonation has important security considerations. Make sure you follow best practices.


Probably the best and the cleanest code that I have seen so far is this:

var credentials = new UserCredentials(domain, username, password);
Impersonation.RunAsUser(credentials, logonType, () =>
{
    // do whatever you want as this user.
});

Just follow Github or Nuget.