ADHelper,一个好用的AD操作类

public class ADHelper
    {
        private static string ADLdapInfo = System.Configuration.ConfigurationManager.AppSettings["ADLdapInfo"].ToString();
        ///扮演类实例
        private static IdentityImpersonation impersonate;

        //private static DirectoryEntry GetDirectoryObject()
        //{
        //    DirectoryEntry entry = null;
        //    if (!string.IsNullOrEmpty(ADLdapInfo))
        //    {
        //        string[] infos = ADLdapInfo.Split(';');
        //        impersonate = new IdentityImpersonation(infos[1], infos[2], "ta-mp");
        //        entry = new DirectoryEntry(infos[0], infos[1], infos[2], AuthenticationTypes.Secure);
        //    }
        //    return entry;
        //}

        ///根据用户帐号称取得用户的 对象
        ///用户帐号名
        ///如果找到该用户,则返回用户的 对象;否则返回 null
        public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
        {
            DirectoryEntry de = null;
            if (!string.IsNullOrEmpty(ADLdapInfo))
            {
                string[] infos = ADLdapInfo.Split(';');
                //允许代码模拟不同的用户
                impersonate = new IdentityImpersonation(infos[1], infos[2], infos[3]);
                impersonate.BeginImpersonate();

                de = new DirectoryEntry(infos[0], infos[1], infos[2], AuthenticationTypes.Secure);
                if (de == null)
                    return null;

                DirectorySearcher deSearch = new DirectorySearcher(de);
                deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(sAMAccountName=" + sAMAccountName + "))";
                deSearch.SearchScope = SearchScope.Subtree;
                try
                {
                    SearchResult result = deSearch.FindOne();
                    de = new DirectoryEntry(result.Path);
                    return de;
                }
                catch{}
                finally
                {
                    impersonate.StopImpersonate();
                }
            }
            return de;
        }

        ///获得指定 指定属性名对应的值
        ///属性名称
        ///属性值        
        public static string GetProperty(DirectoryEntry de, string propertyName)
        {
            string ret = string.Empty;
            string[] infos = ADLdapInfo.Split(';');
            //允许代码模拟不同的用户
            try
            {
                impersonate = new IdentityImpersonation(infos[1], infos[2], infos[3]);
                impersonate.BeginImpersonate();
                if (de.Properties.Contains(propertyName))
                {
                    ret = de.Properties[propertyName][0].ToString();
                }
            }
            catch { }
            finally { impersonate.StopImpersonate(); }
            return ret;
        }
    }

    ///用户模拟角色类。实现在程序段内进行用户角色模拟。
    public class IdentityImpersonation
    {
        [DllImport("advapi32.dll", SetLastError = true)]
        public static extern bool LogonUser(String lpszUsername, String lpszDomain, String lpszPassword, int dwLogonType, int dwLogonProvider, ref IntPtr phToken);

        [DllImport("advapi32.dll", CharSet = CharSet.Auto, SetLastError = true)]
        public extern static bool DuplicateToken(IntPtr ExistingTokenHandle, int SECURITY_IMPERSONATION_LEVEL, ref IntPtr DuplicateTokenHandle);

        [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
        public extern static bool CloseHandle(IntPtr handle);

        // 要模拟的用户的用户名、密码、域(机器名)
        private String _sImperUsername;
        private String _sImperPassword;
        private String _sImperDomain;
        // 记录模拟上下文
        private WindowsImpersonationContext _imperContext;
        private IntPtr _adminToken;
        private IntPtr _dupeToken;
        // 是否已停止模拟
        private Boolean _bClosed;

        ///构造函数
        ///所要模拟的用户的用户名
        ///所要模拟的用户的密码
        ///所要模拟的用户所在的域
        public IdentityImpersonation(String impersonationUsername, String impersonationPassword, String impersonationDomain)
        {
            _sImperUsername = impersonationUsername;
            _sImperPassword = impersonationPassword;
            _sImperDomain = impersonationDomain;

            _adminToken = IntPtr.Zero;
            _dupeToken = IntPtr.Zero;
            _bClosed = true;
        }
       
        ///析构函数
        ~IdentityImpersonation()
        {
            if (!_bClosed)
            {
                StopImpersonate();
            }
        }

        ///开始身份角色模拟。
        public Boolean BeginImpersonate()
        {
            Boolean bLogined = LogonUser(_sImperUsername, _sImperDomain, _sImperPassword, 2, 0, ref _adminToken);

            if (!bLogined)
            {
                return false;
            }

            Boolean bDuped = DuplicateToken(_adminToken, 2, ref _dupeToken);

            if (!bDuped)
            {
                return false;
            }

            WindowsIdentity fakeId = new WindowsIdentity(_dupeToken);
            _imperContext = fakeId.Impersonate();

            _bClosed = false;

            return true;
        }

        ///停止身分角色模拟。
        public void StopImpersonate()
        {
            _imperContext.Undo();
            CloseHandle(_dupeToken);
            CloseHandle(_adminToken);
            _bClosed = true;
        }
    }

原文地址:https://www.cnblogs.com/windy2008/p/2314580.html