2009-09-04 68 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; 
    } 
}