我怎样才能做到这一点?
检查下面的代码,以清楚地描述我正在寻找的内容.
using System.DirectoryServices.AccountManagement;public bool IsUserInOU(string samAccountname,string OUname){ using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIDentity(context,IDentityType.SamAccountname,samAccountname)) { //Check if the user is in the OU specifIEd in OUname //Something like: //return user.IsInOU(OUname); } }}public voID TestIt_1(){ //The parent OU of this user is "AwesomeOU" string samAccountname = "Joe"; string OUname = "AwesomeOU"; bool expected = true; bool actual = IsUserInOU(samAccountname,OUname); Assert.AreEqual(expected,actual);}public voID TestIt_2(){ //The parent OU of this user is "WhateverOU" string samAccountname = "Mike"; string OUname = "AwesomeOU"; bool expected = false; bool actual = IsUserInOU(samAccountname,actual);}
域名:
>国家OU
>真棒OU
乔
>无论OU
>迈克
empi答案后的解决方案1
使用empi给出的信息,我写了以下方法来提取distinguishedname中的第一个OU.做到这一点,其余的是轻而易举.
public static string GetoUForUser(string samAccountname) { using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIDentity(context,samAccountname)) { //System.Console.Writeline(user.distinguishedname); int startIndex = user.distinguishedname.IndexOf("OU=",1) + 3; //+3 for length of "OU=" int endindex = user.distinguishedname.IndexOf(",",startIndex); var group = user.distinguishedname.Substring((startIndex),(endindex - startIndex)); return group; } } }
JPBlanc答复后的解决方案2
public static string GetoUForUser(string samAccountname) { using (var context = new PrincipalContext(ContextType.Domain)) { using (var user = UserPrincipal.FindByIDentity(context,samAccountname)) { using (DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry) { using (DirectoryEntry deUserContainer = deUser.Parent) { return deUserContainer.PropertIEs["name"].Value.ToString(); } } } } }解决方法 Ok @Empi解决方案正在运行,但是UserPrincipal构建在DirectoryEntry对象上,该对象提供了一个父或容器属性,只需要给出您要查找的对象,而不使用字符串方式.
/* Retreiving a principal context */PrincipalContext domainContext = new PrincipalContext(ContextType.Domain,"WM2008R2ENT:389","dc=dom,dc=fr","dom\jpb","MyPwd");/* Retreive a user */UserPrincipal user = UserPrincipal.FindByIDentity(domainContext,"user1");/* Retreive the container */DirectoryEntry deUser = user.GetUnderlyingObject() as DirectoryEntry;DirectoryEntry deUserContainer = deUser.Parent;Console.Writeline (deUserContainer.PropertIEs["distinguishedname"].Value);总结
以上是内存溢出为你收集整理的使用C#获取Active Directory中的用户的父OU全部内容,希望文章能够帮你解决使用C#获取Active Directory中的用户的父OU所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)