2009-09-04 66 views

回答

4

你在.NET 3.5?

如果是這樣,看看這個優秀的MSDN文章Managing Directory Security Principals in the .NET Framework 3.5它顯示了在.NET 3.5的用戶和組管理的新功能。

在這種情況下,你需要一個主要方面(例如,您的域名):

PrincipalContext domainContext = 
    new PrincipalContext(ContextType.Domain, "YourDomain"); 

,然後你可以很容易地找到用戶:

UserPrincipal user = UserPrincipal.FindByIdentity(principalContext, "username"); 

和「UserPrincipal」對象有稱爲「GetAuthorizationGroups」的方法,其返回用戶所屬的所有組:

PrincipalSearchResult<Principal> results = user.GetAuthorizationGroups(); 

// display the names of the groups to which the 
// user belongs 

foreach (Principal result in results) 
{ 
    Console.WriteLine("name: {0}", result.Name); 
} 

P retty容易,呵?

它在.NET很多工作3.5之前,或者在其他語言(PHP,德爾福等)的「直」 LDAP。

馬克

+0

偉大的作品!非常感謝。 – Donut 2009-09-08 13:37:35

1

這裏是另一種方式來獲得組信息:

確保您的System.DirectoryServices添加引用。

DirectoryEntry root = new DirectoryEntry("LDAP://OU=YourOrganizationOU,DC=foo,DC=bar"); 

DirectoryEntry user = GetObjectBySAM("SomeUserName", root); 

if (user != null) 
{ 
    foreach (string g in GetMemberOf(user)) 
    { 
    Console.WriteLine(g); 
    } 
} 

以下方法獲取用戶條目並返回一個字符串列表,它是用戶所屬的組。

public List<string> GetMemberOf(DirectoryEntry de) 
{ 
    List<string> memberof = new List<string>(); 

    foreach (object oMember in de.Properties["memberOf"]) 
    { 
    memberof.Add(oMember.ToString()); 
    } 

    return memberof; 
} 

public DirectoryEntry GetObjectBySAM(string sam, DirectoryEntry root) 
{ 
    using (DirectorySearcher searcher = new DirectorySearcher(root, string.Format("(sAMAccountName={0})", sam))) 
    { 
    SearchResult sr = searcher.FindOne(); 

    if (!(sr == null)) return sr.GetDirectoryEntry(); 
    else 
     return null; 
    } 
}