DirectoryEntry 活动目录的使用

public class DirectoryHelper
    {
        public static string  DomainName = System.Environment.UserDomainName;
        public static string strLDAP = "LDAP://" + DomainName;
        static DirectoryEntry de = new DirectoryEntry(strLDAP);
        /// <summary>
        /// 根据登录名获取用户域fullname
        /// </summary>
        /// <param name="AccountName"></param>
        /// <returns></returns>
        public static string getFullNameByAccountName(string AccountName)
        {
            string FullName = string.Empty;
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = string.Format("(SAMAccountName={0})", AccountName);
            using (HostingEnvironment.Impersonate())
            {
                foreach (SearchResult sr in ds.FindAll())
                {
                    string fullName = sr.GetDirectoryEntry().Name.ToString();
                    //if (sr.GetDirectoryEntry().Properties["samaccountname"].Value.ToString().ToLower() == AccountName)
                    //{
                    FullName = fullName.Substring(3, fullName.Length - 3);
                    // }
                }
            }
            return FullName;
        }

        /// <summary>
        /// 获取所有用户
        /// </summary>
        /// <returns></returns>
        public static DataTable getAllPeople()
        {
            DataTable dt = new DataTable();
            DataColumn dc_accountName = new DataColumn("AccountName", typeof(string));
            DataColumn dc_mail = new DataColumn("Mail", typeof(string));
            DataColumn dc_fullName = new DataColumn("FullName", typeof(string));
            dt.Columns.Add(dc_fullName);
            dt.Columns.Add(dc_accountName);
            dt.Columns.Add(dc_mail);
            DirectorySearcher search = new DirectorySearcher(de);
            search.Filter = "(&(objectClass=user))";
            search.SearchScope = SearchScope.Subtree;
            //模拟用户登录(发布的时候不添加要报错)
            using (HostingEnvironment.Impersonate())
            {
                SearchResultCollection SearchResults = search.FindAll();
                if (SearchResults.Count > 0)
                {
                    foreach (SearchResult sr in SearchResults)
                    {
                        DirectoryEntry GroupEntry = sr.GetDirectoryEntry();
                        string accountName = string.Empty;
                        string fullName = string.Empty;
                        string mail = string.Empty;
                        DataRow dr = dt.NewRow();
                        //先获取邮件属性,如果邮件不是空,说明是要取的部门
                        if (GroupEntry.Properties.Contains("mail"))
                        {
                            mail = GroupEntry.Properties["mail"][0].ToString();
                            dr["Mail"] = mail;
                            if (GroupEntry.Properties.Contains("SAMAccountName"))
                            {
                                accountName = GroupEntry.Properties["SAMAccountName"][0].ToString();
                                dr["AccountName"] = accountName;
                            }
                            if (GroupEntry.Properties.Contains("Name"))
                            {
                                fullName = GroupEntry.Properties["Name"][0].ToString();
                                dr["FullName"] = fullName;
                            }
                            dt.Rows.Add(dr);
                        }
                    }
                }
            }
            return dt;
        }

        /// <summary>
        /// 根据全名获取登录名
        /// </summary>
        /// <param name="fullName"></param>
        /// <returns></returns>
        public static string getAccountNameByFullName(string fullName)
        {
            string accountName = string.Empty;
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = string.Format("(cn={0})", fullName);
            using (HostingEnvironment.Impersonate())
            {
                SearchResult sr = ds.FindOne();
                if (sr != null)
                {
                    if (sr.GetDirectoryEntry().Properties.Contains("samaccountname"))
                    {
                        accountName = sr.Properties["samaccountname"][0].ToString();

                        //accountName = accountName.Substring(3, accountName.Length - 3);
                    }
                }
            }
            return accountName;
        }

        /// <summary>
        /// 判断用户是否存在
        /// </summary>
        /// <param name="FullName"></param>
        /// <returns></returns>
        public static bool checkUserExist(string FullName)
        {
            bool Exist = false;
            DirectorySearcher deSearch = new DirectorySearcher(de);
            deSearch.Filter = "(&(&(objectCategory=person)(objectClass=user))(cn=" + FullName + "))";
            deSearch.SearchScope = SearchScope.Subtree;
            //模拟用户登录(发布的时候不添加要报错)
            using (HostingEnvironment.Impersonate())
            {
                SearchResult result = deSearch.FindOne();
                if (result != null)
                {
                    Exist = true;
                }
                return Exist;
            }
        }

        #region 根据登录名获取用户所在组
        public static DataTable getGroupByAccountName(string AccountName)
        {
            DataTable dt = new DataTable("group");
            DataColumn groupName = new DataColumn("Name", typeof(string));
            dt.Columns.Add(groupName);

            DirectorySearcher search = new DirectorySearcher(de);
            search.Filter = "(&(sAMAccountName=" + AccountName + "))";
            search.PropertiesToLoad.Add("memberof");
            using (HostingEnvironment.Impersonate())
            {
                SearchResult result = search.FindOne();
                if (result == null)
                {
                    DataRow dr = dt.NewRow();
                    dr["Name"] = "暂无数据";
                    dt.Rows.Add(dr);
                }
                else
                {
                    string[] results = new string[result.Properties["memberof"].Count + 1];
                    for (int i = 0; i < result.Properties["memberof"].Count; i++)
                    {
                        string theGroupPath = result.Properties["memberof"][i].ToString();
                        string tempName = theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3);
                        if (tempName == "全体员工" || tempName == "VPN"||tempName=="经理级人员") { }
                        else
                        {
                            DataRow dr = dt.NewRow();
                            dr["Name"] = theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3);
                            dt.Rows.Add(dr);
                        }
                    }
                }
            }
            
            return dt;
        }
        #endregion

        #region 获取it部门成员
        public static DataTable getAllMembersByGroupName(string GroupName)
        {
            DataTable dt_ItMembers = new DataTable();
            DataColumn dc_ItMembers = new DataColumn("Name", typeof(string));
            dt_ItMembers.Columns.Add(dc_ItMembers);

            DirectorySearcher search_ItMember = new DirectorySearcher(de);
            search_ItMember.Filter = "(&(objectClass=group)(cn=" + GroupName + "))";
            //模拟用户登录(发布的时候不添加要报错)
            using (HostingEnvironment.Impersonate())
            {
                SearchResult search_It = search_ItMember.FindOne();
                if (search_It != null)
                {
                    int memberCount = search_It.Properties["member"].Count;
                    for (int i = 0; i < memberCount; i++)
                    {
                        if (!string.IsNullOrEmpty(search_It.Properties["member"][i].ToString()))
                        {
                            string name = search_It.Properties["member"][i].ToString();
                            name = name.Substring(3, name.IndexOf(",") - 3);
                            DataRow dr_itMembersName = dt_ItMembers.NewRow();
                            dr_itMembersName["Name"] = name;
                            dt_ItMembers.Rows.Add(dr_itMembersName);
                        }
                    }
                }
                else
                {
                    DataRow dr_none = dt_ItMembers.NewRow();
                    dr_none["Name"] = "暂无数据";
                    dt_ItMembers.Rows.Add(dr_none);
                }
            }
            return dt_ItMembers;
        }
        #endregion

        #region 获取所有部门
        public static DataTable getAllGroup()
        {
            DataTable dt_group = new DataTable();
            DataColumn dc_group = new DataColumn("GroupName", typeof(string));
            dt_group.Columns.Add(dc_group);

            DirectorySearcher search_ItMember = new DirectorySearcher(de);
            search_ItMember.Filter = "(&(objectClass=group))";
            search_ItMember.SearchScope = SearchScope.Subtree;
            //模拟用户登录(发布的时候不添加要报错)
            using (HostingEnvironment.Impersonate())
            {
                SearchResultCollection SearchResults = search_ItMember.FindAll();
                if (SearchResults.Count > 0)
                {
                    foreach (SearchResult sr in SearchResults)
                    {
                        DirectoryEntry GroupEntry = sr.GetDirectoryEntry();
                        //先获取邮件属性,如果邮件不是空,说明是要取的部门
                        if (GroupEntry.Properties.Contains("mail"))
                        {
                            string mail = GroupEntry.Properties["mail"][0].ToString();
                            if (!string.IsNullOrEmpty(mail))
                            {
                                string groupName = string.Empty;
                                if (GroupEntry.Properties.Contains("Name"))
                                {
                                    groupName = GroupEntry.Properties["Name"][0].ToString();
                                }
                                DataRow dr_group = dt_group.NewRow();
                                dr_group["GroupName"] = groupName;
                                dt_group.Rows.Add(dr_group);
                            }
                        }
                    }
                }
            }
            return dt_group;
        }
        #endregion

        #region 根据全名获取邮箱
        public static string getMailByFullName(string fullName)
        {
            string mail = string.Empty;
            DirectorySearcher ds = new DirectorySearcher(de);
            ds.Filter = "(&(cn=" + fullName + "))";
            using (HostingEnvironment.Impersonate())
            {
                SearchResult result = ds.FindOne();
                if (result != null)
                {
                    mail = result.Properties["mail"][0].ToString();
                }
                return mail;
            }
        }
        #endregion

        /// <summary>
        /// 判断是不是IT部门的人
        /// </summary>
        /// <param name="AccountName"></param>
        /// <returns></returns>
        public static bool IsItGroup(string AccountName)
        {
            bool IsItGroupMember = false;
            
            DirectorySearcher search = new DirectorySearcher(de);
            search.Filter = "(&(sAMAccountName=" + AccountName + "))";
            search.PropertiesToLoad.Add("memberof");
            using (HostingEnvironment.Impersonate())
            {
                SearchResult result = search.FindOne();
                if (result != null)
                {
                    for (int i = 0; i < result.Properties["memberof"].Count; i++)
                    {
                        string theGroupPath = result.Properties["memberof"][i].ToString();
                        if (theGroupPath.Substring(3, theGroupPath.IndexOf(",") - 3) == "IT")
                        {
                            IsItGroupMember = true; return IsItGroupMember;
                        }
                    }
                }
            }
            return IsItGroupMember;
        }
    }
View Code

 

调用:

 //获取当前登录电脑的用户名
string name = System.Environment.UserName.ToLower();
string fullname= DirectoryHelper.getFullNameByAccountName(System.Environment.UserName.ToLower());
bool b_ITGroupMember = DirectoryHelper.IsItGroup(name);

  

 

发布到IIS上后要修改IIS配置

ASP.NET impersonation和window authentication设置成启用,

其他的Annoymous authentication都设置成禁用

应用程序池设置成经典

posted @ 2013-10-16 12:49  老皮肉  阅读(1071)  评论(0编辑  收藏  举报