AD域操作

引入操作类库:

System.DirectoryServices.dll

代码如下:

using System;
using System.Data;
using System.Data.SqlClient;
using System.DirectoryServices;
using System.Security.Principal;
using System.Runtime.InteropServices;
using System.Collections;
using System.Text;


namespace IAD
{
    #region
    /// <summary>
    /// 
    /// </summary>
    public class ADHelper
    {
        #region 私有变量
        private string _user = string.Empty;
        private string _password = string.Empty;
        private string _ldap = string.Empty;
        private string _filterAttribute;

        #endregion

        #region 属性
        /// <summary>
        /// --------------------------
        /// 初始LDAP Path
        ///  -------------------------
        /// </summary>
        public string ADPath
        {
            get
            {
                return _ldap;
            }
            set
            {
                _ldap = value;
            }
        }

        /// <summary>
        /// --------------------------------------------------------
        /// 访问AD的用户,若为空的话就不带用户
        /// --------------------------------------------------------
        /// </summary>
        public string ADUsername
        {
            get
            {
                return _user;
            }
            set
            {
                _user = value;
            }
        }

        /// <summary>
        ///  --------------------------
        /// 访问AD的密码
        ///  --------------------------
        /// </summary>
        public string ADPassword
        {
            get
            {
                return _password;
            }
            set
            {
                _password = value;
            }
        }

        #endregion


        /// <summary>
        /// ---------------------------
        /// 默认构造函数
        /// ---------------------------
        /// </summary>
        public ADHelper()
        {
            this._ldap = "LDAP://DC=minth,DC=intra";
            //this._ldap = "LDAP://rootDSE";
            //this._ldap = "CN=...,...,DC=corp,DC=com";
            this._user = @"MINTH-GlOBAL\SA-HQ-SQL01";
            this._password = "5259mQE49xH8N#4u";
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="user"></param>
        /// <param name="password"></param>
        /// <param name="ladp"></param>
        public ADHelper(string user, string password, string ladp)
        {
            this._user = user;
            this._password = password;
            this._ldap = ladp;
        }

        /// <summary>
        ///  ---------------------------------------------------
        /// 根据User属性返回不同的Entry
        /// ----------------------------------------------------
        /// </summary>
        /// <returns></returns>
        private DirectoryEntry GetRightEntry()
        {
            DirectoryEntry entry;

            if (this.ADUsername != string.Empty)
            {
                entry = new DirectoryEntry(this.ADPath, this.ADUsername, this.ADPassword);
            }
            else
            {
                if (this.ADPath != string.Empty)
                {
                    entry = new DirectoryEntry(this.ADPath);
                }
                else
                {
                    entry = new DirectoryEntry();
                }
            }
            return entry;
        }



        /// <summary>
        /// -------------------------------------------------------
        /// 根据用户名和密码验证在AD中的密码
        /// -------------------------------------------------------
        /// </summary>
        /// <param name="username"></param>
        /// <param name="pwd"></param>
        /// <returns></returns>
        public bool IsAuthenticated(string domain, string username, string pwd)
        {
            string domainAndUsername = domain + @"\" + username;
            DirectoryEntry entry = new DirectoryEntry(this.ADPath, domainAndUsername, pwd);
            try
            {
                //Bind to the native AdsObject to force authentication.
                object obj = entry.NativeObject;
                DirectorySearcher search = new DirectorySearcher(entry);
                search.Filter = "(SAMAccountName=" + username + ")";
                search.PropertiesToLoad.Add("cn");
                SearchResult result = search.FindOne();
                if (null == result)
                {
                    return false;
                }
                // this.ADPath = result.Path;
                _filterAttribute = (string)result.Properties["cn"][0];
            }
            catch (Exception ex)
            {
                // throw new Exception("对用户进行身份验证时出错。 " + ex.Message);
                ex.Message.ToString();
                return false;
            }
            return true;
        }
        /// <summary>
        ///  ----------------------------
        /// 获取AD组信息
        ///  ----------------------------
        /// </summary>
        /// <returns></returns>
        public string GetGroups()
        {
            DirectorySearcher search = new DirectorySearcher(ADPath);
            search.Filter = "(cn=" + _filterAttribute + ")";
            search.PropertiesToLoad.Add("memberOf");
            StringBuilder groupNames = new StringBuilder();

            try
            {
                SearchResult result = search.FindOne();
                int propertyCount = result.Properties["memberOf"].Count;
                string dn;
                int equalsIndex, commaIndex;

                for (int propertyCounter = 0; propertyCounter < propertyCount; propertyCounter++)
                {
                    dn = (string)result.Properties["memberOf"][propertyCounter];
                    equalsIndex = dn.IndexOf("=", 1);
                    commaIndex = dn.IndexOf(",", 1);
                    if (-1 == equalsIndex)
                    {
                        return null;
                    }
                    groupNames.Append(dn.Substring((equalsIndex + 1), (commaIndex - equalsIndex) - 1));
                    groupNames.Append("|");
                }
            }
            catch (Exception ex)
            {
                throw new Exception("Error obtaining group names. " + ex.Message);
            }
            return groupNames.ToString();
        }

        /// <summary>
        ///  ----------------------------------------
        /// 获取默认Domain的LDAP
        ///  ----------------------------------------
        /// </summary>
        /// <returns></returns>
        public string GetDefaultLDAPDomain()
        {
            string ret = string.Empty;
            DirectoryEntry root = GetRightEntry();
            try
            {
                ret = root.Properties["defaultNamingContext"][0].ToString();
            }
            catch (Exception)
            {
                ret = string.Empty;
            }
            root.Close();
            root = null;
            return ret;
        }

        /// <summary>
        /// ----------------------------------------
        /// 根据中文名获取DA帐号
        /// ----------------------------------------
        /// </summary>
        /// <param name="strCN"></param>
        /// <returns></returns>
        public string GetAccoutByCN(string strCN)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;

            string ret = string.Empty;
            try
            {
                search.Filter = ("(cn=" + strCN + ")");
                results = search.FindAll();
                foreach (SearchResult result in results)
                {
                    if (result.Properties["samaccountname"] != null)
                    {
                        return result.Properties["samaccountname"][0].ToString();
                    }
                }
            }
            catch (Exception)
            {
            }
            return string.Empty;

        }


        /// <summary>
        /// ----------------------------------------
        /// 根据DA帐号获取中文名
        /// ----------------------------------------
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public string GetCNByAccount(string account)
        {
            return GetPropertyByAccount(account, "cn");

        }


        /// <summary>
        /// ----------------------------------------
        /// 根据DA帐号获取E-Mail
        /// ----------------------------------------
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public string GetMailByAccount(string account)
        {
            return GetPropertyByAccount(account, "mail");
        }


       

        /// <summary>
        /// ----------------------------------------
        /// 根据DA帐号获取显示名称
        /// ----------------------------------------
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public string GetDisplayNameByAccount(string account)
        {
            return GetPropertyByAccount(account, "displayName");

        }

        /// <summary>
        /// ----------------------------------------
        /// XML特殊符号替换
        /// ----------------------------------------
        /// </summary>
        /// <param name="str"></param>
        /// <returns></returns>
        public static string XmlSpecialReplace(string str)
        {
            str = str.Replace("&", "&amp;");
            str = str.Replace("'", "&apos;");
            str = str.Replace("“”", "&quot;");
            str = str.Replace(">", "&gt;");
            str = str.Replace("<", "&lt;");
            return str;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="eMail"></param>
        /// <returns></returns>
        public string GetAccountByMail(string eMail)
        {
            return GetAccountByMail(eMail, "samaccountname");
        }

        /// <summary>
        /// ---------------------------------------
        /// 根据E-Mail帐号获取AD
        /// --------------------------------------
        /// </summary>
        /// <param name="mail"></param>
        /// <returns></returns>
        private string GetAccountByMail(string eMail, string prop)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;
            string ret = string.Empty;
            try
            {
                search.Filter = ("(mail=" + eMail + ")");
                results = search.FindAll();
                if (results[0].Properties["mail"] != null)
                {
                    ret = XmlSpecialReplace(results[0].Properties[prop][0].ToString());
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                ret = string.Empty;
            }
            return ret;

        }

        /// <summary>
        /// ----------------------------------------
        /// 根据DA帐号获取属性
        /// ----------------------------------------
        /// </summary>
        /// <param name="account"></param>
        /// <param name="prop"></param>
        /// <returns></returns>
        public string GetPropertyByAccount(string account, string prop)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;

            string ret = string.Empty;
            account = ExtractDoamin(account);

            try
            {
                search.Filter = ("(samaccountname=" + account + ")");
                results = search.FindAll();
                if (results[0].Properties["samaccountname"] != null)
                {
                    ret = XmlSpecialReplace(results[0].Properties[prop][0].ToString());
                }
            }
            catch (Exception ex)
            {
                ex.Message.ToString();
                ret = string.Empty;
            }
            return ret;
        }

        /// <summary>
        /// ----------------------------------------
        /// 根据DA帐号判断是存在
        /// ----------------------------------------
        /// </summary>
        /// <param name="account"></param>
        /// <returns></returns>
        public bool IsUserExists(string account)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;

            string ret = string.Empty;
            account = ExtractDoamin(account);
         
            search.Filter = ("(samaccountname=" + account + ")");
            try
            {
                results = search.FindAll();
            }
            catch(Exception ex)
            {
                return false;
            }
            if (results.Count > 0)
                return true;

            return false;
        }


        /// <summary>
        /// -----------------
        ///  //查询CN.
        ///  ----------------
        /// </summary>
        /// <param name="strCN"></param>
        /// <returns></returns>
        public string[] SearchAccountByCN(string strCN)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;

            string ret = string.Empty;
            try
            {
                search.Filter = ("(cn=*" + strCN + "*)");
                results = search.FindAll();
                foreach (SearchResult result in results)
                {
                    if (result.Properties["samaccountname"] != null)
                    {
                        //ret += result.Properties["samaccountname"][0].ToString()+"(" +result.Properties["cn"][0].ToString() + ")" + ";";
                        ret += result.Properties["samaccountname"][0].ToString() + ";";
                    }
                }
            }
            catch (Exception)
            {
                //ret = ret.Trim(';').Split(';');
            }
            return ret.Trim(';').Split(';');
        }

        /// <summary>
        /// ----------------------------------------
        ///Search Account by Account.
        ///----------------------------------------
        /// </summary>
        /// <param name="strAccount"></param>
        /// <returns></returns>
        public string[] SearchAccountByAccount(string strAccount)
        {
            DirectoryEntry root = GetRightEntry();
            DirectorySearcher search = new DirectorySearcher(root);
            SearchResultCollection results;

            string ret = string.Empty;
            try
            {
                search.Filter = ("(samaccountname=*" + strAccount + "*)");
                results = search.FindAll();
                foreach (SearchResult result in results)
                {
                    if (result.Properties["samaccountname"] != null)
                    {
                        ret += result.Properties["samaccountname"][0].ToString() + ";";
                    }
                }
            }
            catch (Exception)
            {
                //ret = ret.Trim(';').Split(';');
            }
            return ret.Trim(';').Split(';');
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public static string ExtractDoamin(string name)
        {
            int n = name.IndexOf("\\");

            //eg. ECCENTRIX\admin 
            if (n > 0)
                name = name.Substring(n + 1);

            return name;
        }



        /// <summary>
        /// 
        /// </summary>
        /// <param name="path"></param>
        /// <returns></returns>
        public Hashtable ListUsers(string path)
        {
            //path = "LDAP://DC=corp,DC=irco,DC=com";
            path = this._ldap;
            DirectoryEntry entry = new DirectoryEntry(path);
            DirectorySearcher searcher = new DirectorySearcher(entry);
            searcher.Filter = "(objectClass=*)";
            searcher.PropertiesToLoad.Clear();
            SearchResultCollection searchResultCollection = searcher.FindAll();
            return VisitSearchResultCollection(searchResultCollection);

        }

        //string messageFormat = "key:{0} value:{1} desc:";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="resultCollection"></param>
        /// <returns></returns>
        public Hashtable VisitSearchResultCollection(SearchResultCollection resultCollection)
        {
            //IList<Users> userList = new List<Users>();
            Hashtable userList = new Hashtable();
            string _userName;
            string _displayName;

            foreach (SearchResult result in resultCollection)
            {
                _userName = string.Empty;
                _displayName = string.Empty;

                ///get username
                if (result.Properties.Contains("samaccountname"))
                {
                    ResultPropertyValueCollection resultValue = result.Properties["samaccountname"];
                    if (resultValue != null && resultValue.Count > 0 && resultValue[0] != null)
                    {
                        _userName = resultValue[0].ToString();
                    }

                }
                ///get displayname
                if (result.Properties.Contains("displayname"))
                {
                    ResultPropertyValueCollection resultValue = result.Properties["displayname"];
                    if (resultValue != null && resultValue.Count > 0 && resultValue[0] != null)
                    {
                        _displayName = resultValue[0].ToString();
                    }
                }
                userList.Add(_userName, _displayName);
            }
            return userList;

        }




    }
    #endregion
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值