我有这个代码可以与群组中的用户一起使用
DirectorySearcher myGroupSearcher = new DirectorySearcher(myDirectoryEntry);
myGroupSearcher.Filter = String.Format("(&(objectClass=group)(|(cn={0})(dn={0})))", strGroupName);
myGroupSearcher.PropertiesToLoad.Add("member");
SearchResult myGroupSearchResult = myGroupSearcher.FindOne();
if (myGroupSearchResult != null)
{
ResultPropertyValueCollection myUsersInGroup = myGroupSearchResult.Properties["member"];
int intMemberCount = myUsersInGroup.Count;
for (int i = 0; i < intMemberCount; i++)
{
//Split the current result
string[] strProperites = myUsersInGroup[i].ToString().Split(',');
//Get the CN
string strUsername = strProperites[0].Substring(3);
DirectorySearcher myUserSearcher = new DirectorySearcher(myDirectoryEntry);
myUserSearcher.Filter = String.Format("(&(objectClass=user)(|(cn={0})(sAMAccountName={0})))", strUsername);
myUserSearcher.PropertiesToLoad.Add("memberOf");
SearchResult myUserSearchResult = myUserSearcher.FindOne();
//Do some work
}
}
这适用于大多数用户,但对于某些用户来说,strUsername会根据客户AD的外观(如果用户有CN包含)进行调整。因此,此解决方案不是最佳使用方式。有没有办法在搜索组中的成员时获取samaccount名称?或者有更好的方法吗?
答案 0 :(得分:7)
假设您使用的是.NET 3.5或更高版本(或者可以升级到它),您应该查看System.DirectoryServices.AccountManagement
(S.DS.AM)命名空间。在这里阅读所有相关内容:
Managing Directory Security Principals in the .NET Framework 3.5
基本上,您可以定义域上下文并轻松在AD中查找用户和/或组:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain);
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
// if found....
if (group != null)
{
// iterate over members
foreach (Principal p in group.GetMembers())
{
Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);
// do whatever you need to do to those members
}
}
新的S.DS.AM使得在AD中使用用户和群组变得非常容易:
答案 1 :(得分:0)
string[] strProperites = myUsersInGroup[i].ToString().Split(new string[] { "cn=" }, StringSplitOptions.RemoveEmptyEntries);
答案 2 :(得分:0)
使用System.DirectoryServices.AccountManagement
类而不是DirectorySearcher可能是一种选择。有一个GroupPrincipal
类,其Members
属性包含UserPrincipal
个对象。