AD域之死

近日所做AD域相关的内容, 从网上淘了不少的代码, 以下代码仍融合两个主要网上AD域操作类集成的. 经测试已经无问题, 希望能大家能有帮助(用的是net1.1,没有用到2.0的部分功能)
ADClass.rar

using System;
using System.Text;
using System.Collections;
using System.DirectoryServices;
using System.Runtime.InteropServices;
using System.Security.Principal;
namespace ActiveDirectory
{
    public sealed class ADHelper
    {
        public static string DomainName = System.Configuration.ConfigurationSettings.AppSettings.Get("Domain");// 域名 "bigmouthz.com"
        public static string ADPath = System.Configuration.ConfigurationSettings.AppSettings.Get("ADPAth");// LDAP绑定路径 "LDAP://bigmouthz.com"
        public static string ADUser = System.Configuration.ConfigurationSettings.AppSettings.Get("ADUser");// 登录帐号 "Administrator"
        public static string ADPassword = System.Configuration.ConfigurationSettings.AppSettings.Get("ADPassword");// 登录密码 "bigmouthz@163.net"
        public static string ADInitPassword = System.Configuration.ConfigurationSettings.AppSettings.Get("ADInitPassword");// 初始密码 "bigmouthz@163.net"
        //public static string ADUsersPath = System.Configuration.ConfigurationSettings.AppSettings.Get("ADUsersPath");//
        ///// LDAP 地址
        //static string LDAPDomain = "DC=MyDomain,DC=local";
        private static IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
        public enum LoginResult
        {
            /// 正常登录
            LOGIN_USER_OK = 0,
            /// 用户不存在
            LOGIN_USER_DOESNT_EXIST,
            /// 用户帐号被禁用
            LOGIN_USER_ACCOUNT_INACTIVE,
            /// 用户密码不正确
            LOGIN_USER_PASSWORD_INCORRECT
        }
        #region "public Enums"
        internal enum UserStatus
        {
            Enable = 544,
            Disable = 546
        }
        internal enum GroupScope
        {
            ADS_GROUP_TYPE_DOMAIN_LOCAL_GROUP = -2147483644,
            ADS_GROUP_TYPE_GLOBAL_GROUP = -2147483646,
            ADS_GROUP_TYPE_UNIVERSAL_GROUP = -2147483640
        }
        internal enum ADAccountOptions
        {
            UF_TEMP_DUPLICATE_ACCOUNT = 256,
            UF_NORMAL_ACCOUNT = 512,
            UF_INTERDOMAIN_TRUST_ACCOUNT = 2048,
            UF_WORKSTATION_TRUST_ACCOUNT = 4096,
            UF_SERVER_TRUST_ACCOUNT = 8192,
            UF_DONT_EXPIRE_PASSWD = 65536,
            UF_SCRIPT = 1,
            UF_ACCOUNTDISABLE = 2,
            UF_HOMEDIR_REQUIRED = 8,
            UF_LOCKOUT = 16,
            UF_PASSWD_NOTREQD = 32,
            UF_PASSWD_CANT_CHANGE = 64,
            UF_ACCOUNT_LOCKOUT = 16,
            UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 128
        }

        #endregion
        public enum ADS_USER_FLAG_ENUM
        {
            /// 登录脚本标志。如果通过 ADSI LDAP 进行读或写操作时,该标志失效。如果通过 ADSI WINNT,该标志为只读。
            ADS_UF_SCRIPT = 0X0001,
            /// 用户帐号禁用标志
            ADS_UF_ACCOUNTDISABLE = 0X0002,
            /// 主文件夹标志
            ADS_UF_HOMEDIR_REQUIRED = 0X0008,
            /// 过期标志
            ADS_UF_LOCKOUT = 0X0010,
            /// 用户密码不是必须的
            ADS_UF_PASSWD_NOTREQD = 0X0020,
            /// 密码不能更改标志
            ADS_UF_PASSWD_CANT_CHANGE = 0X0040,
            /// 使用可逆的加密保存密码
            ADS_UF_ENCRYPTED_TEXT_PASSWORD_ALLOWED = 0X0080,
            /// 本地帐号标志
            ADS_UF_TEMP_DUPLICATE_ACCOUNT = 0X0100,
            /// 普通用户的默认帐号类型
            ADS_UF_NORMAL_ACCOUNT = 0X0200,
            /// 跨域的信任帐号标志
            ADS_UF_INTERDOMAIN_TRUST_ACCOUNT = 0X0800,
            /// 工作站信任帐号标志
            ADS_UF_WORKSTATION_TRUST_ACCOUNT = 0x1000,
            /// 服务器信任帐号标志
            ADS_UF_SERVER_TRUST_ACCOUNT = 0X2000,
            /// 密码永不过期标志
            ADS_UF_DONT_EXPIRE_PASSWD = 0X10000,
            /// MNS 帐号标志
            ADS_UF_MNS_LOGON_ACCOUNT = 0X20000,
            /// 交互式登录必须使用智能卡
            ADS_UF_SMARTCARD_REQUIRED = 0X40000,
            /// 当设置该标志时,服务帐号(用户或计算机帐号)将通过 Kerberos 委托信任
            ADS_UF_TRUSTED_FOR_DELEGATION = 0X80000,
            /// 当设置该标志时,即使服务帐号是通过 Kerberos 委托信任的,敏感帐号不能被委托
            ADS_UF_NOT_DELEGATED = 0X100000,
            /// 此帐号需要 DES 加密类型
            ADS_UF_USE_DES_KEY_ONLY = 0X200000,
            /// 不要进行 Kerberos 预身份验证
            ADS_UF_DONT_REQUIRE_PREAUTH = 0X4000000,
            /// 用户密码过期标志
            ADS_UF_PASSWORD_EXPIRED = 0X800000,
            /// 用户帐号可委托标志
            ADS_UF_TRUSTED_TO_AUTHENTICATE_FOR_DELEGATION = 0X1000000
        }

        public ADHelper()
        {
            //
        }

        #region GetDirectoryObject

        public static DirectoryEntry GetDirectoryObject()
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath, ADUser, ADPassword, AuthenticationTypes.Secure);
            return entry;
        }

        public static DirectoryEntry GetDirectoryObject(string userName, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath, userName, password, AuthenticationTypes.None);
            return entry;
        }

        public static DirectoryEntry GetDirectoryObject(string domainReference)
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, ADUser, ADPassword, AuthenticationTypes.Secure);
            return entry;
        }

        public static DirectoryEntry GetDirectoryObject(string domainReference, string userName, string password)
        {
            DirectoryEntry entry = new DirectoryEntry(ADPath + domainReference, userName, password, AuthenticationTypes.Secure);
            return entry;
        }

        #endregion

        #region GetDirectoryEntry

        public static DirectoryEntry GetDirectoryEntry(string commonName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = new DirectoryEntry(result.Path);
                return de;
            }
            catch
            {
                return null;
            }
        }

        public static DirectoryEntry GetDirectoryEntry(string commonName, string password)
        {
            DirectoryEntry de = GetDirectoryObject(commonName, password);
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = new DirectoryEntry(result.Path);
                return de;
            }
            catch
            {
                return null;
            }
        }

        public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName)
        {
            DirectoryEntry de = GetDirectoryObject();
            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
            {
                return null;
            }
        }

        public static DirectoryEntry GetDirectoryEntryByAccount(string sAMAccountName, string password)
        {
            DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
            if (de != null)
            {
                string commonName = de.Properties["cn"][0].ToString();

                if (GetDirectoryEntry(commonName, password) != null)
                    return GetDirectoryEntry(commonName, password);
                else
                    return null;
            }
            else
            {
                return null;
            }
        }

        public static DirectoryEntry GetDirectoryEntryOfGroup(string groupName)
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(objectClass=group)(cn=" + groupName + "))";
            deSearch.SearchScope = SearchScope.Subtree;

            try
            {
                SearchResult result = deSearch.FindOne();
                de = new DirectoryEntry(result.Path);
                return de;
            }
            catch
            {
                return null;
            }
        }

        #endregion

        #region GetProperty

        public static string GetProperty(DirectoryEntry de, string propertyName)
        {
            if (de.Properties.Contains(propertyName))
            {
                return de.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        public static string GetProperty(SearchResult searchResult, string propertyName)
        {
            if (searchResult.Properties.Contains(propertyName))
            {
                return searchResult.Properties[propertyName][0].ToString();
            }
            else
            {
                return string.Empty;
            }
        }

        #endregion

        public static void SetProperty(DirectoryEntry de, string propertyName, string propertyValue)
        {
            if (propertyValue != string.Empty || propertyValue != "" || propertyValue != null)
            {
                if (de.Properties.Contains(propertyName))
                {
                    de.Properties[propertyName][0] = propertyValue;
                    //?????de.Properties[propertyName].Value = propertyValue;
                }
                else
                {
                    de.Properties[propertyName].Add(propertyValue);
                }
            }
        }

        public static bool CreateNewUser(ADUser user)
        {
            return CreateNewUser(user, ADInitPassword);
        }

        public static bool CreateNewUser(ADUser user, string password)
        {
            try
            {
                CreateNewUser(user.Name, user.SAMAccountName, password);
                UpdateUser(user);
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        public static DirectoryEntry CreateNewUser(string ldapDN, string commonName, string sAMAccountName, string password)
        {
            DirectoryEntry entry = GetDirectoryObject();
            DirectoryEntry subEntry = entry.Children.Find(ldapDN);
            DirectoryEntry deUser = subEntry.Children.Add("CN=" + commonName, "user");
            deUser.Properties["sAMAccountName"].Value = sAMAccountName;
            deUser.CommitChanges();
            EnableUser(commonName);
            SetPassword(commonName, password);
            deUser.Close();
            return deUser;
        }

        public static DirectoryEntry CreateNewUser(string commonName, string sAMAccountName, string password)
        {
            return CreateNewUser("CN=Users", commonName, sAMAccountName, password);
        }

        public static DirectoryEntry CreateNewUser(string commonName, string password)
        {
            return CreateNewUser("CN=Users", commonName, commonName, password);
        }

        public static bool UpdateUser(ADUser user)
        {
            try
            {
                impersonate.BeginImpersonate();

                DirectoryEntry de = ADHelper.GetDirectoryEntryByAccount(user.SAMAccountName);
                //ADHelper.SetProperty(de, "AccountExpires", user.AccountExpires);
                //ADHelper.SetProperty(de, "AdminCount", user.AdminCount);
                //ADHelper.SetProperty(de, "BadPasswordTime", user.BadPasswordTime);
                //ADHelper.SetProperty(de, "BadPwdCount", user.BadPwdCount);
                //ADHelper.SetProperty(de, "C", user.C);
                 //ADHelper.SetProperty(de, "CodePage", user.CodePage);
                //ADHelper.SetProperty(de, "CountryCode", user.CountryCode);
                //ADHelper.SetProperty(de, "DistinguishedName", user.DistinguishedName);
                //ADHelper.SetProperty(de, "HomeDirectory", user.HomeDirectory);
                //ADHelper.SetProperty(de, "HomeDrive", user.HomeDrive);
                //ADHelper.SetProperty(de, "LastLogoff", user.LastLogoff);
                //ADHelper.SetProperty(de, "LastLogon", user.LastLogon);
                //ADHelper.SetProperty(de, "LastLogonTimestamp", user.LastLogonTimestamp);
                //ADHelper.SetProperty(de, "LogonCount", user.LogonCount);
                //ADHelper.SetProperty(de, "LogonHours", user.LogonHours);
                //ADHelper.SetProperty(de, "Manager", user.Manager);
                //ADHelper.SetProperty(de, "ObjectGUID", user.ObjectGUID);
                //ADHelper.SetProperty(de, "ObjectSid", user.ObjectSid);
                //ADHelper.SetProperty(de, "ProfilePath", user.ProfilePath);
                //ADHelper.SetProperty(de, "PwdLastSet", user.PwdLastSet);
                //ADHelper.SetProperty(de, "SAMAccountType", user.SAMAccountType);
                //ADHelper.SetProperty(de, "ScriptPath", user.ScriptPath);
                //ADHelper.SetProperty(de, "UserWorkstations", user.UserWorkstations);
                //ADHelper.SetProperty(de, "USNChanged", user.USNChanged);
                //ADHelper.SetProperty(de, "USNCreated", user.USNCreated);
                //ADHelper.SetProperty(de, "WhenChanged", user.WhenChanged);
                //ADHelper.SetProperty(de, "WhenCreated", user.WhenCreated);

                if (user.CO != null && user.CO != "") ADHelper.SetProperty(de, "CO", user.CO);
                if (user.Company != null && user.Company != "") ADHelper.SetProperty(de, "Company", user.Company);
                if (user.Department != null && user.Department != "") ADHelper.SetProperty(de, "Department", user.Department);
                if (user.DisplayName == null || user.DisplayName == "") user.DisplayName = user.Name; ADHelper.SetProperty(de, "DisplayName", user.DisplayName);
                if (user.FacsimileTelephoneNumber != null && user.FacsimileTelephoneNumber != "") ADHelper.SetProperty(de, "FacsimileTelephoneNumber", user.FacsimileTelephoneNumber);
                if (user.GivenName != null && user.GivenName != "") ADHelper.SetProperty(de, "givenName", user.GivenName);
                if (user.HomePhone != null && user.HomePhone != "") ADHelper.SetProperty(de, "HomePhone", user.HomePhone);
                if (user.Info != null && user.Info != "") ADHelper.SetProperty(de, "Info", user.Info);
                if (user.Initials != null && user.Initials != "") ADHelper.SetProperty(de, "Initials", user.Initials);
                if (user.IpPhone != null && user.IpPhone != "") ADHelper.SetProperty(de, "IpPhone", user.IpPhone);
                if (user.L != null && user.L != "") ADHelper.SetProperty(de, "L", user.L);
                if (user.Mail != null && user.Mail != "") ADHelper.SetProperty(de, "Mail", user.Mail);
                if (user.Mobile != null && user.Mobile != "") ADHelper.SetProperty(de, "Mobile", user.Mobile);
                if (user.Pager != null && user.Pager != "") ADHelper.SetProperty(de, "Pager", user.Pager);
                if (user.PhysicalDeliveryOfficeName != null && user.PhysicalDeliveryOfficeName != "") ADHelper.SetProperty(de, "PhysicalDeliveryOfficeName", user.PhysicalDeliveryOfficeName);
                if (user.PostalCode != null && user.PostalCode != "") ADHelper.SetProperty(de, "PostalCode", user.PostalCode);
                if (user.PostOfficeBox != null && user.PostOfficeBox != "") ADHelper.SetProperty(de, "PostOfficeBox", user.PostOfficeBox);
                if (user.SN != null && user.SN != "") ADHelper.SetProperty(de, "SN", user.SN);
                if (user.ST != null && user.ST != "") ADHelper.SetProperty(de, "ST", user.ST);
                if (user.StreetAddress != null && user.StreetAddress != "") ADHelper.SetProperty(de, "StreetAddress", user.StreetAddress);
                if (user.TelephoneNumber != null && user.TelephoneNumber != "") ADHelper.SetProperty(de, "TelephoneNumber", user.TelephoneNumber);
                if (user.Title != null && user.Title != "") ADHelper.SetProperty(de, "Title", user.Title);
                if (user.UserPrincipalName == null || user.UserPrincipalName == "") user.UserPrincipalName = user.Name + "@" + ADHelper.DomainName; ADHelper.SetProperty(de, "UserPrincipalName", user.UserPrincipalName);
                if (user.WWWHomePage != null && user.WWWHomePage != "") ADHelper.SetProperty(de, "WWWHomePage", user.WWWHomePage);

                //ADHelper.SetProperty(de, "SAMAccountName", user.SAMAccountName);
                 //ADHelper.SetProperty(de, "Name", user.Name);
                //ADHelper.SetProperty(de, "CN", user.CN);
                //ADHelper.SetProperty(de, "UserAccountControl", user.UserAccountControl);
                //if (user.IsAccountActive == true)
                //{
                //    //de.Properties["userAccountControl"][0] = ADHelper.UserStatus.Enable;
                //    de.Properties["userAccountControl"].Value = ADHelper.UserStatus.Enable;
                //}
                //else
                //{
                //    //de.Properties["userAccountControl"][0] = ADHelper.UserStatus.Disable;
                //    de.Properties["userAccountControl"].Value = ADHelper.UserStatus.Disable;
                //}

                de.CommitChanges();
                impersonate.StopImpersonate();
                de.Close();
                return true;
            }
            catch (Exception ex)
            {
                //throw (new Exception("User cannot be updated" + ex.Message));
                return false;
            }
        }

        public static bool UpdateGroup(ADGroup group)
        {
            try
            {
                impersonate.BeginImpersonate();
                DirectoryEntry de = ADHelper.GetDirectoryEntryOfGroup(group.Name);
                ADHelper.SetProperty(de, "DisplayName", group.DisplayName);
                ADHelper.SetProperty(de, "Description", group.Description);
                de.CommitChanges();
                impersonate.StopImpersonate();
                de.Close();
                return true;
            }
            catch (Exception ex)
            {
                //throw (new Exception("User cannot be updated" + ex.Message));
                return false;
            }
        }

        public static bool IsUserExists(string commonName)
        {
           try
           {
              DirectoryEntry de = GetDirectoryObject();
              DirectorySearcher deSearch = new DirectorySearcher(de);
              deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + commonName + "))";       // LDAP 查询串
              SearchResultCollection results = deSearch.FindAll();

              if (results.Count == 0)
                 return false;
              else
                 return true;
           }
           catch (Exception)
           {
              return false;
           }
        }

        public static bool IsUserValid(string UserName, string Password)
        {
            try
            {
                DirectoryEntry deUser = GetDirectoryObject(UserName, Password);
                deUser.Close();
                return true;
            }
            catch (Exception)
            {
                return false;
            }
        }

        public static bool IsAccountActive(string UserName)
        {
            ADUser user = GetUser(UserName);
            return user.IsAccountActive;
        }

        //public static bool IsAccountActive(int userAccountControl)
        //{
        //    int userAccountControl_Disabled = Convert.ToInt32(ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE);
        //    int flagExists = userAccountControl & userAccountControl_Disabled;

        //    if (flagExists > 0)
        //        return false;
        //    else
        //        return true;
        //}

        internal static bool IsAccountActive(int userAccountControl)
        {
            int userAccountControl_Disabled = Convert.ToInt32(ADAccountOptions.UF_ACCOUNTDISABLE);
            int flagExists = userAccountControl & userAccountControl_Disabled;
            if (flagExists > 0)
            {
                return false;
            }
            else
            {
                return true;
            }
        }

        public static LoginResult Login(string commonName, string password)
        {
            DirectoryEntry de = GetDirectoryEntry(commonName);

            if (de != null)
            {
                int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
                de.Close();

                if (!IsAccountActive(userAccountControl))
                    return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;

                if (GetDirectoryEntry(commonName, password) != null)
                    return LoginResult.LOGIN_USER_OK;
                else
                    return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
            }
            else
            {
                return LoginResult.LOGIN_USER_DOESNT_EXIST;
            }
        }

        public static LoginResult LoginByAccount(string sAMAccountName, string password)
        {
            DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);

            if (de != null)
            {
                int userAccountControl = Convert.ToInt32(de.Properties["userAccountControl"][0]);
                de.Close();
                if (!IsAccountActive(userAccountControl)) return LoginResult.LOGIN_USER_ACCOUNT_INACTIVE;

                if (GetDirectoryEntryByAccount(sAMAccountName, password) != null)
                    return LoginResult.LOGIN_USER_OK;
                else
                    return LoginResult.LOGIN_USER_PASSWORD_INCORRECT;
            }
            else
            {
                return LoginResult.LOGIN_USER_DOESNT_EXIST;
            }
        }

        public static bool SetPassword(string commonName, string newPassword)
        {
            try
            {
                DirectoryEntry de = GetDirectoryEntry(commonName);
                impersonate.BeginImpersonate();
                de.Invoke("SetPassword", new object[] { newPassword });
                impersonate.StopImpersonate();
                de.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }

        }

        public static bool SetPasswordByAccount(string sAMAccountName, string newPassword)
        {
            try
            {
                DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
                IdentityImpersonation impersonate = new IdentityImpersonation(ADUser, ADPassword, DomainName);
                impersonate.BeginImpersonate();
                de.Invoke("SetPassword", new object[] { newPassword });
                impersonate.StopImpersonate();
                de.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        public static bool ChangeUserPassword(string commonName, string oldPassword, string newPassword)
        {
            try
            {
                // to-do: 需要解决密码策略问题
                DirectoryEntry oUser = GetDirectoryEntry(commonName);
                oUser.Invoke("ChangePassword", new Object[] { oldPassword, newPassword });
                oUser.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        public static bool EnableUser(string commonName)
        {
            try
            {
                EnableUser(GetDirectoryEntry(commonName));
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        private static void EnableUser(DirectoryEntry de)
        {
            impersonate.BeginImpersonate();
            //de.Properties["userAccountControl"][0] = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD;
            de.Properties["userAccountControl"].Value = UserStatus.Enable;

            de.CommitChanges();
            impersonate.StopImpersonate();
            de.Close();
        }

        public static bool DisableUser(string commonName)
        {
            try
            {
                DisableUser(GetDirectoryEntry(commonName));
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        private static void DisableUser(DirectoryEntry de)
        {
            impersonate.BeginImpersonate();
            //de.Properties["userAccountControl"][0] = ADS_USER_FLAG_ENUM.ADS_UF_NORMAL_ACCOUNT | ADS_USER_FLAG_ENUM.ADS_UF_DONT_EXPIRE_PASSWD | ADS_USER_FLAG_ENUM.ADS_UF_ACCOUNTDISABLE;
            de.Properties["userAccountControl"].Value = UserStatus.Disable;
            de.CommitChanges();
            impersonate.StopImpersonate();
            de.Close();
        }

        public static bool AddUserToGroup(string userCommonName, string groupName)
        {
            try
            {
                DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
                DirectoryEntry oUser = GetDirectoryEntry(userCommonName);

                impersonate.BeginImpersonate();
                oGroup.Properties["member"].Add(oUser.Properties["distinguishedName"].Value);
                oGroup.CommitChanges();
                impersonate.StopImpersonate();

                oGroup.Close();
                oUser.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        public static bool RemoveUserFromGroup(string userCommonName, string groupName)
        {
            try
            {
                DirectoryEntry oGroup = GetDirectoryEntryOfGroup(groupName);
                DirectoryEntry oUser = GetDirectoryEntry(userCommonName);

                impersonate.BeginImpersonate();
                oGroup.Properties["member"].Remove(oUser.Properties["distinguishedName"].Value);
                oGroup.CommitChanges();
                impersonate.StopImpersonate();

                oGroup.Close();
                oUser.Close();
                return true;
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return false;
            }
        }

        #region new
        public static ADUser GetUser(string commonName)
        {
            DirectoryEntry de = GetDirectoryEntry(commonName);
            ADUser ADUser = ADUser.Load(de);
            return ADUser;
        }

        public static ADUser GetUser(string commonName, string password)
        {
            DirectoryEntry de = GetDirectoryEntry(commonName, password);
            ADUser ADUser = ADUser.Load(de);
            return ADUser;
        }

        public static ADUser GetUserByAccount(string sAMAccountName)
        {
            DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName);
            ADUser ADUser = ADUser.Load(de);
            return ADUser;
        }

        public static ADUser GetUserByAccount(string sAMAccountName, string password)
        {
            DirectoryEntry de = GetDirectoryEntryByAccount(sAMAccountName, password);
            ADUser ADUser = ADUser.Load(de);
            return ADUser;
        }


        public static ADGroup GetGroup(string groupName)
        {
            DirectoryEntry de = GetDirectoryEntryOfGroup(groupName);
            ADGroup ADGroup = ADGroup.Load(de);
            return ADGroup;
        }

        internal static DirectoryEntry GetDirectoryObjectByDistinguishedName(string ObjectPath)
        {
            DirectoryEntry oDE;
            oDE = new DirectoryEntry(ObjectPath, ADUser, ADPassword, AuthenticationTypes.Secure);
            return oDE;
        }

        private static SearchResultCollection GetUsers()
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectClass=user)(objectCategory=person))";
            deSearch.SearchScope = SearchScope.Subtree;
            return deSearch.FindAll();
        }
        private static SearchResultCollection GetGroups()
        {
            DirectoryEntry de = GetDirectoryObject();
            DirectorySearcher deSearch = new DirectorySearcher();
            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectClass=group))";
            return deSearch.FindAll();
        }
        private static ArrayList LoadGroups(SearchResultCollection seCollection)
        {
            ArrayList list = new ArrayList();
            ADGroup adGroup;
            foreach (SearchResult se in seCollection)
            {
                adGroup = ADGroup.Load(new DirectoryEntry(se.Path, ADUser, ADPassword, AuthenticationTypes.Secure));
                list.Add(adGroup);
            }
            return list;
        }
        private static ArrayList LoadUsers(SearchResultCollection seCollection)
        {
            ArrayList list = new ArrayList();
            ADUser adUser;
            foreach (SearchResult se in seCollection)
            {
                adUser = ActiveDirectory.ADUser.Load(new DirectoryEntry(se.Path, ADUser, ADPassword, AuthenticationTypes.Secure));
                list.Add(adUser);
            }
            return list;
        }

        public static ArrayList LoadAllGroups()
        {
            return LoadGroups(GetGroups());
        }

        public static ArrayList LoadAllUsers()
        {
            return LoadUsers(GetUsers());
        }

       public static string GetStrGroups()
       {
          StringBuilder list = new StringBuilder();
          try
          {
             ArrayList algroups = ADHelper.LoadAllGroups();
             for (int i = 0, cnt = algroups.Count; i < cnt; i++)
             {
                ADGroup g = (ADGroup)algroups[i];
                list.Append(g.Name);
                list.Append("|");
             }
             list.Length -= 1;
          }
          catch (Exception ex)
          {
             System.Console.WriteLine(ex.Message);
          }
          return list.ToString();
       }


        public static string GetGroupUsers(string groupName)
        {
            try
            {
                StringBuilder list = new StringBuilder();
                ADGroup group = GetGroup(groupName);
                for (int i = 0, cnt = group.Users.Count; i < cnt; i++)
                {
                    ADUser u = (ADUser)group.Users[i];
                    list.Append(u.Name);
                    list.Append(":");
                    list.Append(u.DisplayName);
                    list.Append("|");
                }
                list.Length -= 1;//remove the last '|' symbol
                return list.ToString();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return String.Empty;
            }
        }

        public static string GetUserGroups(string userName)
        {
            try
            {
                StringBuilder list = new StringBuilder();
                ADUser user = GetUser(userName);
                for (int i = 0, cnt = user.Groups.Count; i < cnt; i++)
                {
                    ADGroup g = (ADGroup)user.Groups[i];
                    list.Append(g.Name);
                    list.Append("|");
                }
                list.Length -= 1;//remove the last '|' symbol
                return list.ToString();
            }
            catch (Exception ex)
            {
                System.Console.WriteLine(ex.Message);
                return String.Empty;
            }
        }

        #endregion

    }

    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/bigmouthz/p/1033943.html