AD访问类库

AD访问类库

        项目中要求使用AD帐号登陆我们的系统,同时要就用户的一些信息,显示在系统上。为了方便以后复用代码。我在网上搜集了一些资料,写成的类库。

        做完以后,信息的读取很像数据库的读取,关键是设置DirectorySearcher的Filter,和SearchScope属性。暂时整理出AD的属性列表(好像2000server和2003Server有些出入)。以后又时间我会整理出来,也希望能购得到大家的帮助。

using System;
using System.Collections.Generic;
using System.Text;

namespace CLBADQuery
{
    //
    // Active directoy Query 类库
    // 包括AD的查询,浏览,导出,自定义查询等操作.
    // 参考资料 : www
    // Protocol : LDAP
    // Auther : GJG
    // Mail : xiaojiong1983@gmail.com
    // Web  : xiaojiong.xinwen365.net
    // Date : 2006-8-28
    //
    public class ADQuery
    {
        public string m_strLastError = "";
        public ADQuery()
        {
            m_strLastError = "No error";
        }
        public string GetLastError()
        {
            return m_strLastError;
        }
        public string ExtractUserName(string path)
        {
            string[] userPath = path.Split(new char[] { '//' });

            if (0 >= userPath.Length)
            {
                return "";
            }
            else
            {
                return userPath[userPath.Length - 1];
            }
        }
        public string ExtractOUName(string path)
        {
            string[] userPath = path.Split(new char[] { '=' });
            if (0 >= userPath.Length)
            {
                return "";
            }
            else
            {
                return userPath[userPath.Length - 1];
            }
        }
        public string ExtractGroupName(string path)
        {
            string[] userPath = path.Split(new char[] { '=' });
            string[] strGroup = userPath[1].Split(new char[] { ',' });

            if (0 > strGroup.Length)
            {
                return "";
            }
            else
            {
                return strGroup[0];
            }
        }
        public static bool UserExists(System.DirectoryServices.DirectoryEntry de,
                                        string UserName)
        {
            //create instance fo the direcory searcher
            System.DirectoryServices.DirectorySearcher deSearch = new System.DirectoryServices.DirectorySearcher();

            //set the search filter
            deSearch.SearchRoot = de;
            deSearch.Filter = "(&(objectClass=user) (cn=" + UserName + "))";

            //find the first instance
            System.DirectoryServices.SearchResultCollection results = deSearch.FindAll();

            //if the username and password do match, then this implies a valid login
            //if so then return the DirectoryEntry object
            if (results.Count == 0)
            {
                return false;
            }
            else
            {
                return true;
            }

        }
        //
        // 登陆AD
        //
        public System.DirectoryServices.DirectoryEntry LogonDC(string strPath,
                                        string strUserName, string strPsw)
        {
            System.DirectoryServices.DirectoryEntry deEntry =
                                new System.DirectoryServices.DirectoryEntry();

            deEntry.Path = "LDAP://" + strPath;
            deEntry.Password = strPsw;
            deEntry.Username = strUserName;

            return deEntry;
        }
        //
        // 获得活动目录当前目录下的Group
        //
        public System.Collections.ArrayList GetAllGroupList(string strPath,
                                        string strName, string strPsw)
        {
            System.Collections.ArrayList alGroupList =
                                new System.Collections.ArrayList();
            System.DirectoryServices.DirectoryEntry deEntry =
                                new System.DirectoryServices.DirectoryEntry();

            deEntry.Path = strPath;
            deEntry.Username = strName;
            deEntry.Password = strPsw;
            System.DirectoryServices.DirectorySearcher search =
                            new System.DirectoryServices.DirectorySearcher();
            // search.Filter = "!(objectClass=user)";
            search.SearchRoot = deEntry;
            search.PropertiesToLoad.Add("CN");
            search.SearchScope = System.DirectoryServices.SearchScope.OneLevel;

            try
            {
                System.DirectoryServices.SearchResultCollection resultCol = search.FindAll();
                if (resultCol != null)
                {
                    if (resultCol.Count > 0)
                    {
                        foreach (System.DirectoryServices.SearchResult Result in resultCol)
                        {
                            string strDetailInfo = "";
                            if (strPath == Result.Path)
                            {
                                continue;
                            }
                            if (Result.Properties.Contains("cn"))
                            {
                                strDetailInfo += Result.Properties["cn"][0].ToString();
                                // if (UserExists(deEntry, strDetailInfo))
                                {
                                    // continue;
                                }
                                alGroupList.Add((strDetailInfo));
                            }

                        }
                    }
                }
            }
            catch (Exception ex)
            {
                m_strLastError = ex.Message;
            }
            finally
            {
                deEntry.Close();
            }

            return alGroupList;
        }
        //
        // 获得AD下的Group
        //
        public System.Collections.ArrayList GetALLGroupList(System.DirectoryServices.DirectoryEntry deEntry)
        {
            System.Collections.ArrayList alGroupList = new System.Collections.ArrayList();

            foreach (System.DirectoryServices.DirectoryEntry dir in deEntry.Children)
            {
                if (dir.SchemaClassName != "container")
                {
                    continue;
                }
                System.DirectoryServices.DirectoryEntry searchRoot = dir;

                alGroupList.Add(ExtractGroupName(dir.Name));

                searchRoot.Close();
            }

            return alGroupList;
        }
        //
        // 获得活动目录下的OU
        //
        public System.Collections.ArrayList GetAllOUList(string strPath, string strUserName, string strPsw)
        {
            System.Collections.ArrayList alOUList = new System.Collections.ArrayList();
            System.DirectoryServices.DirectoryEntry deEntry = new System.DirectoryServices.DirectoryEntry();
            string strOUName;
            string strDCName;

            deEntry.Path = strPath;
            deEntry.Username = strUserName;
            deEntry.Password = strPsw;

            try
            {
                foreach (System.DirectoryServices.DirectoryEntry deOU in deEntry.Children)
                {
                    strDCName = deOU.SchemaClassName.ToString();
                    if (strDCName == "organizationalUnit")
                    {
                        strOUName = deOU.Name.ToString();
                        alOUList.Add(ExtractOUName(strOUName));
                    }

                    deOU.Close();
                }
            }
            catch (Exception ex)
            {
                alOUList.Add(ex.Message);
            }
            finally
            {
                deEntry.Close();
            }
            return alOUList;
        }
        //
        // 搜索AD详细信息
        // 返回格式
        //          [0]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //          [1]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //          [n]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //
        public System.Collections.ArrayList GetGroupUserDetail(string strPath, string strUserName,
                                                    string strPsw, string strGroupName)
        {
            System.Collections.ArrayList alDetail = new System.Collections.ArrayList();

            System.DirectoryServices.DirectoryEntry deEntry =
                            new System.DirectoryServices.DirectoryEntry();

            deEntry.Path = strPath;
            deEntry.Password = strPsw;
            deEntry.Username = strUserName;

            string strDetailInfo = "";

            System.DirectoryServices.DirectorySearcher search =
                    new System.DirectoryServices.DirectorySearcher(deEntry);

            search.Filter = "(&(objectClass=user)(objectCategory=person))";

            search.PropertiesToLoad.Add("sn");
            search.PropertiesToLoad.Add("name");
            search.PropertiesToLoad.Add("displayname");
            search.PropertiesToLoad.Add("title");
            search.PropertiesToLoad.Add("telephoneNumber");
            search.PropertiesToLoad.Add("mail");
            search.PropertiesToLoad.Add("department");
            search.PropertiesToLoad.Add("memberOf");
            search.PropertiesToLoad.Add("SAMAccountName");

            search.SearchScope = System.DirectoryServices.SearchScope.OneLevel;
            System.DirectoryServices.SearchResult result;
            System.DirectoryServices.SearchResultCollection resultCol = search.FindAll();
            if (resultCol != null)
            {
                for (int counter = 0; counter < resultCol.Count; counter++)
                {
                    result = resultCol[counter];

                    strDetailInfo = "";
                    //
                    // 帐号
                    //
                    if (result.Properties.Contains("SAMAccountName"))
                    {
                        strDetailInfo += result.Properties["SAMAccountName"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }
                    //
                    // 姓名
                    //
                    if (result.Properties.Contains("name"))
                    {
                        strDetailInfo += result.Properties["name"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 部门
                    //
                    if (result.Properties.Contains("department"))
                    {
                        strDetailInfo += result.Properties["department"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 职务
                    //
                    if (result.Properties.Contains("title"))
                    {
                        strDetailInfo += result.Properties["title"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 电子邮件
                    //
                    if (result.Properties.Contains("mail"))
                    {
                        strDetailInfo += result.Properties["mail"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 联系电话
                    //
                    if (result.Properties.Contains("telephoneNumber"))
                    {
                        strDetailInfo += result.Properties["telephoneNumber"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 属组
                    //
                    if (result.Properties.Contains("memberOf"))
                    {
                        string strTemp = result.Properties["memberOf"][0].ToString();

                        int i = strTemp.IndexOf("CN=" + strGroupName + ",");
                        if (strGroupName != "Domain Users" &&
                            i != 0)
                        {
                            continue;
                        }
                        strDetailInfo += result.Properties["memberOf"][0].ToString() + "-";
                    }
                    else
                    {
                        // continue;
                        strDetailInfo += "none-";
                    }
                    //
                    // 扩展属性
                    //
                    if (result.Properties.Contains("employeeID"))
                    {
                        strDetailInfo += result.Properties["employeeID"][0].ToString();
                    }
                    else
                    {
                        strDetailInfo += "none";
                    }
                    alDetail.Add(strDetailInfo);
                }
            }
            return alDetail;
        }
        //
        // 搜索AD详细信息
        // 返回格式
        //          [0]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //          [1]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //                      ................................
        //          [n]帐号-姓名-部门-职务-电子邮件-联系电话-属组-扩展属性
        //
        public System.Collections.ArrayList GetOUUserDetailInfo(string strPath, string strUserName,
                                string strPsw)
        {
            System.Collections.ArrayList alDetail = new System.Collections.ArrayList();

            System.DirectoryServices.DirectoryEntry deEntry = new System.DirectoryServices.DirectoryEntry();

            deEntry.Path = strPath;
            deEntry.Password = strPsw;
            deEntry.Username = strUserName;

            string strDetailInfo = "";

            System.DirectoryServices.DirectorySearcher search =
                    new System.DirectoryServices.DirectorySearcher(deEntry);

            search.Filter = "(objectClass=user)";

            search.PropertiesToLoad.Add("sn");
            search.PropertiesToLoad.Add("name");
            search.PropertiesToLoad.Add("displayname");
            search.PropertiesToLoad.Add("title");
            search.PropertiesToLoad.Add("telephoneNumber");
            search.PropertiesToLoad.Add("mail");
            search.PropertiesToLoad.Add("department");
            search.PropertiesToLoad.Add("memberOf");
            search.PropertiesToLoad.Add("SAMAccountName");
            search.PropertiesToLoad.Add("employeeID");

            search.SearchScope = System.DirectoryServices.SearchScope.Subtree;


            System.DirectoryServices.SearchResult result;
            System.DirectoryServices.SearchResultCollection resultCol = search.FindAll();
            if (resultCol != null)
            {
                for (int counter = 0; counter < resultCol.Count; counter++)
                {
                    result = resultCol[counter];

                    strDetailInfo = "";
                    //
                    // 帐号
                    //
                    if (result.Properties.Contains("SAMAccountName"))
                    {
                        strDetailInfo += result.Properties["SAMAccountName"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }
                    //
                    // 姓名
                    //
                    if (result.Properties.Contains("name"))
                    {
                        strDetailInfo += result.Properties["name"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 部门
                    //
                    if (result.Properties.Contains("department"))
                    {
                        strDetailInfo += result.Properties["department"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 职务
                    //
                    if (result.Properties.Contains("title"))
                    {
                        strDetailInfo += result.Properties["title"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 电子邮件
                    //
                    if (result.Properties.Contains("mail"))
                    {
                        strDetailInfo += result.Properties["mail"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 联系电话
                    //
                    if (result.Properties.Contains("telephoneNumber"))
                    {
                        strDetailInfo += result.Properties["telephoneNumber"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none-";
                    }

                    //
                    // 属组
                    //
                    if (result.Properties.Contains("memberOf"))
                    {
                        strDetailInfo += result.Properties["memberOf"][0].ToString() + "-";
                    }
                    else
                    {
                        strDetailInfo += "none" + "-";
                    }
                    //
                    // 扩展属性
                    //
                    if (result.Properties.Contains("employeeID"))
                    {
                        strDetailInfo += result.Properties["employeeID"][0].ToString();
                    }
                    else
                    {
                        strDetailInfo += "none";
                    }
                    alDetail.Add(strDetailInfo);
                }
            }
            return alDetail;
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值