如果您使用 .NET 3.5 或更高版本,则可以使用新的 System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间,这比以前更容易。
在此处阅读所有相关信息:Managing Directory Security Principals in the .NET Framework 3.5
更新: 很遗憾,较早的 MSDN 杂志文章不再在线 - 您需要来自 Microsoft 的 download the CHM for the January 2008 MSDN magazine 并阅读其中的文章。
基本上,您需要有一个“主体上下文”(通常是您的域)、一个用户主体,然后您就可以很容易地获得它的组:
public List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if(user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
// iterate over all groups
foreach(Principal p in groups)
{
// make sure to add only group principals
if(p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}
return result;
}
仅此而已!您现在有了用户所属的授权组的结果(列表) - 遍历它们,打印出它们的名称或您需要做的任何事情。
更新: 为了访问UserPrincipal 对象上未显示的某些属性,您需要深入了解底层DirectoryEntry:
public string GetDepartment(Principal principal)
{
string result = string.Empty;
DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
return result;
}
更新 #2: 将这两个 sn-ps 代码放在一起似乎应该不会太难......但是没关系 - 就这样吧:
public string GetDepartment(string username)
{
string result = string.Empty;
// if you do repeated domain access, you might want to do this *once* outside this method,
// and pass it in as a second parameter!
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);
// if user is found
if(user != null)
{
// get DirectoryEntry underlying it
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
}
return result;
}