Run Code as a different user

Vaccano picture Vaccano · Jul 23, 2009 · Viewed 90.8k times · Source

Is there a way to tell my code to run as a different user?

I am calling NetUserSetInfo via a PInvoke and I need to call it as a different user. Is there a way to do that?

Answer

Milan Matějka picture Milan Matějka · May 26, 2015

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.