解决方案:-
这是您可以从 AD 中的 OU 获取组的方法
DataTable dt = new DataTable();
dt.Columns.Add("groups");
DirectoryEntry rootDSE = null;
假设我想从我的部门 OU 获取记录。现在路径会是这样
部门-->>用户
这里的dc是域控制器名称,在我的例子中是Corp.Local
这样你就可以从你的 AD 中获取组
if (department != "")
{
rootDSE = new DirectoryEntry(
"LDAP://OU=" + department + ",OU=Users,dc=corp,dc=local", username, password);
}
else
{
rootDSE = new DirectoryEntry(
"LDAP://OU=Users,OU=" + ou + ",dc=corp,dc=local", username, password);
}
DirectorySearcher ouSearch = new DirectorySearcher(rootDSE);
ouSearch.PageSize = 1001;
ouSearch.Filter = "(objectClass=group)";
ouSearch.SearchScope = SearchScope.Subtree;
ouSearch.PropertiesToLoad.Add("name");
SearchResultCollection allOUS = ouSearch.FindAll();
foreach (SearchResult oneResult in allOUS)
{
dt.Rows.Add(oneResult.Properties["name"][0].ToString());
}
rootDSE.Dispose();
return dt;
现在如何将用户添加到组中。
这是单个用户的示例,您可以通过循环用户以类似的方式执行此操作。
PrincipalContext pr = new PrincipalContext(ContextType.Domain,
"corp.local", "dc=corp,dc=local", username, password);
GroupPrincipal group = GroupPrincipal.FindByIdentity(pr, groupName);//Looking for the Group in AD Server
if (group == null)
{
//Throw Exception
}
UserPrincipal user = UserPrincipal.FindByIdentity(pr, userName);//Looking for the User in AD Server
if (user.IsMemberOf(group))//If Group is already added to the user
{
//I have Put it into If else condition because in case you want to Remove Groups from that User you can write your Logic here.
//Do Nothing, Because the group is already added to the user
}
else// Group not found in the Current user,Add it
{
if (user != null & group != null)
{
group.Members.Add(user);
group.Save();
done = user.IsMemberOf(group);//You can confirm it from here
}
}
pr.Dispose();
return done;