public Impersonate(LogonType logonType, string username, string domain, string password) { if (logonType == LogonType.None) { return; } _context = new ImpersonationContext(); uint error = _context.ImpersonateValidUser(logonType, username, domain, password); if (error != 0) { throw new Exception($@"Cannot impersonate {domain}\{username} as {logonType} Error: {error}"); } }
public static bool Run(Action action, LogonType logonType, string username, string domain, string password) { ImpersonationContext context = new ImpersonationContext(); try { uint error = context.ImpersonateValidUser(logonType, username, domain, password); if (error == 0) { action.Invoke(); return(true); } } finally { context.UndoImpersonation(); } return(false); }