博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

C#读取ActiveDirectory

Posted on 2020-05-09 10:31  筑筑  阅读(354)  评论(0编辑  收藏  举报
 public class ActiveDirectoryManager
    {
        public static DirectoryEntry GetDirectoryEntry()
        {
            DirectoryEntry entry = null;
            try
            {
                if (entry == null)
                {
                    entry = new DirectoryEntry(ActiveDirectoryHelper.ADString, ActiveDirectoryHelper.ADUserName, ActiveDirectoryHelper.ADPassWord, AuthenticationTypes.Secure);
                }
                return entry;
            }
            catch (Exception ex)
            {

                throw ex;
            }
        }

        public static DirectorySearcher GetDirectorySearcher(DirectoryEntry entry)
        {
            DirectorySearcher searcher = null;
            try
            {
                if (searcher == null)
                {
                    searcher = new DirectorySearcher(entry)
                    {
                        CacheResults = true,
                        SearchScope = SearchScope.Subtree
                    };
                    var propertys = ActiveDirectoryHelper.ADProperty.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                    searcher.PropertiesToLoad.Clear();
                    foreach (var item in propertys)
                    {
                        searcher.PropertiesToLoad.Add(item);
                    }
                }
                return searcher;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }

    public class ActiveDirectoryHelper
    {
        public static string ADString = ConfigurationManager.ConnectionStrings["ADConnectionString"].ConnectionString;

        public static string ADUserName = ConfigurationManager.AppSettings["ADUsername"];

        public static string ADPassWord = ConfigurationManager.AppSettings["ADPassword"];

        public static string ADProperty = ConfigurationManager.AppSettings["ADProperty"];

        public static string ADKey = ConfigurationManager.AppSettings["ADKey"];

        public static string ADUserWhere = ConfigurationManager.AppSettings["ADUserWhere"].Replace("", "&");

        public static List<object> GetDirectoryInfo(DirectorySearcher searcher, string userName = null, string userCode = null)
        {
            var where = string.Empty;
            if (!string.IsNullOrWhiteSpace(userName) || !string.IsNullOrWhiteSpace(userCode))
            {
                where = string.Format(ADUserWhere, userName == null ? string.Empty : userName, userCode == null ? string.Empty : userCode);
            }
            else
            {
                where = "(&(objectClass=user))";
            }
                
            return ExecuteDataSource(searcher, where);
        }

        private static List<object> ExecuteDataSource(DirectorySearcher searcher, string where)
        {
            if (!string.IsNullOrWhiteSpace(where)) searcher.Filter = where;

            SearchResultCollection result = searcher.FindAll();
            Func<SearchResult, bool> basicWhere = x => true;
            var keys = ADKey.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in keys)
            {
                basicWhere += x => !string.IsNullOrWhiteSpace(x.Properties.Get<string>(item));
            }

            //return result.OfType<SearchResult>().Where(x => !ResultOrEmpty(x)).Select(x => GetDynamic(x)).ToList();
            //var SearchResults = result.OfType<SearchResult>().Where(basicWhere);
            var propertys = ADProperty.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            return result.OfType<SearchResult>().Select(x => GetDynamic(x, propertys)).Where(x=>x != null).ToList();
        }

        private static object GetDynamic(SearchResult result,string[] propertys)
        {
            dynamic info = new ExpandoObject();

            var dic = (IDictionary<string, object>)info;

            //var propertys = ADProperty.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            var keys = ADKey.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
            foreach (var item in propertys)
            {
                if (string.IsNullOrWhiteSpace(result.Properties.Get<string>(item)) && keys.Contains(item))
                {
                    return null;
                }
                dic.Add(item, result.Properties.Get<string>(item));
            }
            return info;
        }

        private static bool ResultOrEmpty(SearchResult result)
        {
            bool isEmpty = false;

            var keys = ADKey.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

            foreach (var item in keys)
            {
                if (string.IsNullOrWhiteSpace(result.Properties.Get<string>(item)))
                {
                    isEmpty = true;
                    break;
                }

            }
            return isEmpty;
        }

    }

    public static class ResultPropertyCollectionExtension
    {
        public static T Get<T>(this ResultPropertyCollection target, string propertyName)
        {
            if (target == null)
                throw new ArgumentNullException("target");

            if (string.IsNullOrEmpty(propertyName))
                throw new ArgumentNullException("propertyName");

            if (target.Contains(propertyName) && target[propertyName].Count > 0)
                return (T)target[propertyName][0];
            return default(T);
        }
    }