/// <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 Task RunImpersonatedAsync(IntPtr token, bool loadUserProfile, ImpersonatedActionAsync action) { if (action == null) { throw new ArgumentNullException(nameof(action)); } if (token == IntPtr.Zero) { throw new ArgumentException("The token is zero.", nameof(token)); } return(WindowsUser.RunImpersonatedAsync <object>(token, loadUserProfile, async(ptr, identity, profile) => { await action(ptr, identity, profile); return null; })); }