#region 根据当前登录域账号 获取AD用户姓名和所在OU目录 ////// 根据当前登录域账号 获取AD用户姓名和所在OU目录 返回域用户是否存在 /// /// 要搜索的当前用户名 /// out返回该用户所在OU目录 /// out 返回该用户的姓名 ///搜索域用户是否存在 public static bool GetADUserNameAndPaths(string searchUser, out Listpaths, out string userName) { bool isExite = false;//该域用户是否 存在。。。 DataContextProvider.loger.Info(string.Format(">>>>>>>>>>>>>>>>>>>>>>>>>>>获取当前域用户信息log>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>start>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>")); DirectoryEntry entry = null; string name = "未知"; List directorys = null; try { //读取配置文件...连接登录域服务器 //"LDAP://10.2.17.*" 域服务器地址 //登录名 //密码 DataContextProvider.loger.Info(string.Format("域服务地址:{0}、、域账号:{1}、、域密码{2}、、", ConfigHelper.DomainAddress, ConfigHelper.DomainAccount, ConfigHelper.DomainPassWord)); using (entry=new DirectoryEntry(ConfigHelper.DomainAddress, ConfigHelper.DomainAccount, ConfigHelper.DomainPassWord, AuthenticationTypes.Secure)) { if (entry != null) { DirectorySearcher mySearcher = new DirectorySearcher(entry); mySearcher.Filter = ("(&(|(objectClass=user)(objectClass=organizationalUnit)(objectClass=group))(|(cn=" + searchUser + ")(dn=" + searchUser + ")(sAMAccountName=" + searchUser + ")))"); // ("(&(objectClass=organizationalUnit)(OU=电力技术部))"); SearchResult searchResult = mySearcher.FindOne(); if (searchResult != null) { isExite = true;//该域用户 存在。。。 string path = searchResult.Path; DataContextProvider.loger.Info(string.Format("获取当前登录域账号的OUPath>>>>>>>>>>>>>>>>>>>>>>>>>>>{0}", path)); string[] splits = path.Split(new char[] { ',' }); for (int i = splits.Count() - 1; i >= 0; i--) { if (splits[i].Contains("OU=")) { if (directorys==null) { directorys = new List (); } directorys.Add(splits[i].Substring(splits[i].IndexOf('=') + 1)); } } string xing = (string)(searchResult.Properties["sn"].Count>0?searchResult.Properties["sn"][0]:""); string ming = (string)(searchResult.Properties["givenname"].Count>0?searchResult.Properties["givenname"][0]:""); name = (xing + ming); DataContextProvider.loger.Info(string.Format("获取当前登录域账号的姓名>>>>>>>属性>>>>>name>>>>>>>>>>>>>>>{0}", name)); } } } } catch (Exception ex) { DataContextProvider.loger.Error(" 获取AD用户姓名和所在OU目录 发生异常:: " + ex.ToString()); } //finally //{ // //释放资源 // entry.Close(); // entry.Dispose(); //} paths = directorys; userName = name; return isExite; } #endregion
参考: