How to perform Impersonated task at run time in c#.


To perform Impersonated task at run time we need a authorized USERID and PASSWORD and domain name.
We can’t pass parameters to the method which needs to be impersonated. We have taken a method name AddInterger which needs to be replaced by your method name.

 PerformImpersonatedTask(UserId, Domain, PWD,
                       LOGON32_LOGON_INTERACTIVE,
                       LOGON32_PROVIDER_DEFAULT,
                       new Action(AddInterger));

Add below lines of code in your code page.

#region Consts

public const int LOGON32_LOGON_INTERACTIVE = 2;
public const int LOGON32_PROVIDER_DEFAULT = 0;

#endregion

#region External API
[DllImport("advapi32.dll", SetLastError = true)]
public static extern int LogonUser(
    string lpszUsername, string lpszDomain,
    string lpszPassword, int dwLogonType,
    int dwLogonProvider, out IntPtr phToken
    );

[DllImport("advapi32.dll", SetLastError = true)]
public static extern bool RevertToSelf();

[DllImport("kernel32.dll", SetLastError = true)]
public static extern int CloseHandle(IntPtr hObject);

#endregion

#region Methods

public void PerformImpersonatedTask(string username, string domain,
    string password, int logonType, int logonProvider, Action methodToPerform)
{
    IntPtr token = IntPtr.Zero;
    if (RevertToSelf())
    {
        if (LogonUser(username, domain, password, logonType,
            logonProvider, out token) != 0)
        {
            var identity = new WindowsIdentity(token);
            var impersonationContext = identity.Impersonate();
            if (impersonationContext != null)
            {
                methodToPerform.Invoke();
                impersonationContext.Undo();

            }
        }
        else
        {
            // do logging
        }
    }
    if (token != IntPtr.Zero)
    {
        CloseHandle(token);
    }
}

#endregion