2012-02-28 326 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