Example #1
0
        /// <summary>
        /// Impersonates a passed Windows Identity
        /// </summary>
        /// <param name="identity"></param>
        public static void ImpersonateAndRun(WindowsIdentity identity, bool loadProfile, Action action)
        {
            if (loadProfile)
            {
                var systemUtil        = new SystemUtils();
                var domainAndUsername = new string[2];
                var utilsMisc         = new Miscellaneous();
                domainAndUsername = utilsMisc.FormatDomainAndUsername(identity.Name);
                var userName = domainAndUsername[1];
                if (!systemUtil.LoadProfile(identity.Token, userName))
                {
                    throw new Exception("LoadProfile failed. " + "Win32 Error Code: " + Marshal.GetLastWin32Error() + "|| Message: " + new Win32Exception(Marshal.GetLastWin32Error()).Message);
                }
            }

            WindowsIdentity.RunImpersonated(identity.AccessToken, () =>
            {
                action.Invoke();
            });
        }