/// <summary> /// Performs a user impersonation based on a logon token. /// </summary> /// <param name="token"> The logon token. </param> /// <param name="loadUserProfile"> Specifies whether the users profile is to be loaded. </param> /// <param name="action"> The code to run under the impersonated user. </param> /// <exception cref="ArgumentNullException"> <paramref name="action" /> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="token" /> is zero. </exception> /// <exception cref="SecurityException"> The current user does not have sufficient permissions. </exception> /// <exception cref="Win32Exception"> /// The current user does not have sufficient permissions or the impersonation could not /// be completed. /// </exception> public static void RunImpersonated(IntPtr token, bool loadUserProfile, ImpersonatedAction action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (token == IntPtr.Zero) { throw new ArgumentException("The token is zero.", nameof(token)); } WindowsUser.RunImpersonated <object>(token, loadUserProfile, (ptr, identity, profile) => { action(ptr, identity, profile); return(null); }); }