在好例子网,分享、交流、成长!
您当前所在位置:首页C# 开发实例常用C#方法 → AD 操作 Helper类代码下载

AD 操作 Helper类代码下载

常用C#方法

下载此实例
  • 开发语言:C#
  • 实例大小:3.10KB
  • 下载次数:15
  • 浏览次数:211
  • 发布时间:2016-04-21
  • 实例类别:常用C#方法
  • 发 布 人:allenwang
  • 文件格式:.zip
  • 所需积分:2
 相关标签: 操作AD

实例介绍

【实例简介】
【实例截图】

【核心代码】

using System;
using System.Collections.Generic;
using System.DirectoryServices;
using System.Globalization;
using System.Linq;
using System.Text;

namespace COM.VNet.BSS.CommonUtility
{
    public class DomainHelper
    {
        private DomainHelper(string domainName)
        {
            _domainName = domainName;
        }


        public static DomainHelper CreateActiveDirectoryConsole(string domainName, string userName, string passWord)
        {
            if (_console == null)
            {
                _console = new DomainHelper(domainName);

                _domainName = domainName;
                _userName = userName;
                _passWord = passWord;
            }
            else
            {
                if (_domainName != domainName)
                {
                    _console = new DomainHelper(domainName);

                    _domainName = domainName;
                    _userName = userName;
                    _passWord = passWord;
                }
            }

            return _console;
        }


        #region 字段
        private static DomainHelper _console;

        private static string _domainName;
        private static string _userName;
        private static string _passWord;
        #endregion


        #region 方法
        /// <summary>
        /// 根据OU的名字,获取看当前OU下面的组信息
        /// </summary>
        /// <param name="ouName">OU的名字</param>
        /// <returns></returns>
        private string[] GetGroup(string ouName)
        {
            string[] groups;

            var adRoot = GetDirectoryEntry();

            var ou = adRoot.Children.Find("OU="   ouName);

            var mySearcher = new DirectorySearcher(ou)
                {
                    Filter = ("(objectClass=group)"),
                    SearchScope = SearchScope.Subtree
                };

            //user表示用户,group表示组
            var src = mySearcher.FindAll();

            if (src.Count > 0)
            {
                groups = new string[src.Count];

                for (var i = 0; i < src.Count; i  )
                {
                    var group = src[i].GetDirectoryEntry();

                    if (group.Properties.Contains("Name"))
                    {
                        groups[i] = group.Properties["Name"][0].ToString();
                    }
                }
            }
            else
            {
                groups = null;
            }

            return groups;
        }

        private DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry domain = string.IsNullOrEmpty(_userName) ? 
                                        new DirectoryEntry("LDAP://"   _domainName) : 
                                        new DirectoryEntry("LDAP://"   _domainName, _userName
                                                           , _passWord, AuthenticationTypes.Secure);

            return domain;
        }

        private IList<ADUserInformation> GetUsers(string groupName)
        {
            var list = new List<ADUserInformation>();

            var domain = GetDirectoryEntry();

            var domainSearcher = new DirectorySearcher(domain) {Filter = "(&(objectClass=group)(cn="   groupName   "))"};
            var group = domainSearcher.FindOne().GetDirectoryEntry();

            var sb = new StringBuilder();
            sb.Append("(|");

            using (@group)
            {
                foreach (string s in @group.Properties["member"])
                {
                    sb.AppendFormat("(distinguishedName={0})", s);
                }
            }

            sb.Append(")");

            var searchRoot = domain;

            using (searchRoot)
            {
                var ds = new DirectorySearcher(searchRoot, sb.ToString(), new[] {"Name", "SAMAccountName"});

                using (var users = ds.FindAll())
                {
                    var userlist = (from SearchResult user in users
                                    where user.Properties["SAMAccountName"].Count > 0
                                    select user);

                    list.AddRange(userlist.Select(MappingDomainUserInformation));
                }
            }
            return list;
        }

        private static ADUserInformation MappingDomainUserInformation(SearchResult user)
        {
            var groups = user.Properties["memberof"];
            var userGroups = (from object @group in groups
                             from item in @group.ToString().Split(',')
                             select item.ToString(CultureInfo.InvariantCulture).Split('=')
                                 into paris
                                 where paris.Any() && paris[0] == "CN"
                                 select paris[1]).ToList();

            var AccountName = GetDomainProperty(user, "SAMAccountName");
            var email = AccountName   "@21vianet.com";
#if DEBUG
            email = "yong.ding@hisoft.com";
#endif
            return new ADUserInformation
                {
                    AccountName = AccountName,
                    Name = GetDomainProperty(user, "DisplayName", "Name"),
                    ADPath = GetDomainProperty(user, "adspath"),
                    Groups = userGroups,
                    Email = email,
                    Phone = GetDomainProperty(user, "telephonenumber"),
                    CN = GetDomainProperty(user, "CN"),
                    OU = GetDomainProperty(user, "OU")
                };
        }

        /// <summary>
        /// 获取AD域中查询结果的Property,如果传入一个Property直接查询,如果传入两个Property ,则当第一个值为空时查询第二个值
        /// </summary>
        /// <param name="user">Ad域查询结果</param>
        /// <param name="property1">要查询的数据</param>
        /// <param name="property2">备选属性</param>
        /// <returns></returns>
        private static string GetDomainProperty(SearchResult user, string property1, string property2 = "")
        {
            string value1 = string.Empty, value2 = string.Empty;

            if (user.Properties.Contains(property1))
            {
                value1 = user.Properties[property1][0].ToString();
            }
            if (!string.IsNullOrEmpty(property2))
            {
                if (user.Properties.Contains(property2))
                {
                    value2 = user.Properties[property2][0].ToString();
                }
            }

            if (string.IsNullOrEmpty(property2))
            {
                return value1;
            }

            return !string.IsNullOrEmpty(value1) ? value1 : value2;
        }

        public string GetADUserNameForBJOE(string accountName)
        {
            var userInfo = GetUser("bj-oe", accountName);
            if (userInfo != null)
            {
                return userInfo.Name;
            }

            return string.Empty;
        }

        public ADUserInformation GetUser(string ouName, string userName)
        {
            ADUserInformation retVal = null;

            var adRoot = GetDirectoryEntry();

            var ou = adRoot.Children.Find("OU="   ouName);

            var domainSearcher = new DirectorySearcher(ou) { Filter = "(&(objectCategory=person)(objectClass=user))" };

            using (ou)
            {
                var users = domainSearcher.FindAll();
                SearchResult user = users.Cast<SearchResult>().
                    FirstOrDefault(item => item.Properties.Contains("SAMAccountName") 
                        && item.Properties["SAMAccountName"][0].ToString() == userName);

                if (user != null)
                {
                   
                    retVal = MappingDomainUserInformation(user);
                }

            }

            return retVal;
        }

        public Dictionary<string, ADUserInformation> GetAdUserList(string[] ouList)
        {
            var userList = new List<ADUserInformation>();

            string[] ous = ouList;

            if (ous.Length > 0)
            {
                var groupList = new List<string>();

                foreach (var groups in ous.Select(GetGroup).Where(groups => groups != null && groups.Length > 0))
                {
                    groupList.AddRange(groups);
                }

                foreach (var t in groupList)
                {
                    IList<ADUserInformation> users;

                    try
                    {
                        users = GetUsers(t);
                    }
                    catch (Exception)
                    {
                        continue;
                    }

                    if (users != null && users.Count > 0)
                    {
                        userList.AddRange(users);
                    }
                }
            }
            else
            {
                throw new Exception("OU表中没有有效的数据!");
            }

            var userDir = new Dictionary<string, ADUserInformation>();

            foreach (var item in userList)
            {
                if (userDir.ContainsKey(item.AccountName))
                {
                    if (userDir[item.AccountName].Groups == null)
                    {
                        userDir[item.AccountName].Groups = new List<string>();
                    }

                    userDir[item.AccountName].Groups =
                            userDir[item.AccountName].Groups.Concat(item.Groups).ToList();
                }
                else
                {
                    userDir.Add(item.AccountName, item);
                }
            }

            return userDir;
        }

        public IList<ADUserInformation> GetGroupUserList(string ouName, string selectedGroupName)
        {
            var groupList = GetGroup(ouName).Where(groups => !string.IsNullOrEmpty(groups)).ToList();
            if (!groupList.Contains(selectedGroupName))
            {
                throw new Exception(string.Format("当前OU中不存在指定的组。OU:{0}  Group:{1}", ouName, selectedGroupName));
            }

            IList<ADUserInformation> userList = GetUsers(selectedGroupName);

            return userList;
        }


        public List<string> GetAdGroupList(string[] ouList)
        {
            var groupList = new List<string>();

            foreach (string[] groups in ouList.Select(GetGroup).Where(groups => groups != null && groups.Length > 0))
            {
                groupList.AddRange(groups);
            }

            return groupList;
        }


        #endregion
    }
}

标签: 操作AD

实例下载地址

AD 操作 Helper类代码下载

不能下载?内容有错? 点击这里报错 + 投诉 + 提问

好例子网口号:伸出你的我的手 — 分享

网友评论

发表评论

(您的评论需要经过审核才能显示)

查看所有0条评论>>

小贴士

感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。

  • 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
  • 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
  • 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
  • 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。

关于好例子网

本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明

;
报警