2012-02-28 327 views
6

我正在尝试获取将作为程序输入的特定域的用户信息。在域名的基础上,它应该返回用户名称/或NT Id和SID的列表。我是ldap编程的新手,任何人都可以帮助我获得此列表。如何通过ldap中的域名获取用户的用户名和SID

+2

当你说* LDAP *,你的意思是*的Active Directory *在Windows上,还是需要对所有可能的LDAP服务器.... – 2012-02-28 05:51:08

回答

15

如果您使用的是.NET 3.5或更高版本,并且正在讨论Active Directory,那么您应该查看System.DirectoryServices.AccountManagement(S.DS.AM)命名空间。在这里阅读全部内容:

基本上,你可以定义域范围内,并可以轻松地查找用户和/或组AD:

// set up domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// find a user 
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName"); 

if(user != null) 
{ 
    // do something here....  
    var usersSid = user.Sid; 

    // not sure what you mean by "username" - the "DisplayName" ? The "SAMAccountName"?? 
    var username = user.DisplayName; 
    var userSamAccountName = user.SamAccountName; 
} 

的新的S.DS.AM可以很容易地与AD中的用户和群组玩耍!

更新:如果通过域的所有用户需要循环 - 试试这个:

您可以使用PrincipalSearcher和“查询通过例如”主要做你的搜索:

// create your domain context 
PrincipalContext ctx = new PrincipalContext(ContextType.Domain); 

// define a "query-by-example" principal - here, we search for a UserPrincipal 
UserPrincipal qbeUser = new UserPrincipal(ctx); 

// create your principal searcher passing in the QBE principal  
PrincipalSearcher srch = new PrincipalSearcher(qbeUser); 

// find all matches 
foreach(var found in srch.FindAll()) 
{ 
    UserPrincipal user = found as UserPrincipal; 

    if(user != null) 
    { 
     // do whatever here 
     var usersSid = user.Sid; 

     // not sure what you mean by "username" - the "DisplayName" ? 
     var username = user.DisplayName; 
     var userSamAccountName = user.SamAccountName; 
    } 
} 

更新#2:如果你不能(或不愿)使用S.DS.AM方法 - 这是最简单的,为Active Directory,迄今为止 - 那么你需要回落到System.DirectoryServices课程和方法:

// define the root of your search 
DirectoryEntry root = new DirectoryEntry("LDAP://dc=YourCompany,dc=com"); 

// set up DirectorySearcher 
DirectorySearcher srch = new DirectorySearcher(root); 
srch.Filter = "(objectCategory=Person)"; 
srch.SearchScope = SearchScope.Subtree; 

// define properties to load 
srch.PropertiesToLoad.Add("objectSid"); 
srch.PropertiesToLoad.Add("displayName"); 

// search the directory 
foreach(SearchResult result in srch.FindAll()) 
{ 
    // grab the data - if present 
    if(result.Properties["objectSid"] != null && result.Properties["objectSid"].Count > 1) 
    { 
     var sid = result.Properties["objectSid"][0]; 
    } 

    if(result.Properties["displayName"] != null && result.Properties["displayName"].Count > 0) 
    { 
     var userName = result.Properties["displayName"][0].ToString(); 
    } 
} 
+0

喜,感谢名单答复“通用” LDAP解决方案..但在我的情况下,我不会定义任何用户..它应该是循环通过为每个用户的一个perticular域.. – Eshwer 2012-02-28 06:21:22

+0

@Eshwer:更新我的回应,通过一个给定域的所有**用户循环 - 这个**如果你有很多用户,**会很慢。 – 2012-02-28 06:24:36

+0

嗨..但是你在哪里指定ldap网址..?或者它不是必需的?在这种情况下,它将从哪里获取用户列表? – Eshwer 2012-02-28 06:31:29