解決方案: -
這是如何從一個OU在AD
DataTable dt = new DataTable();
dt.Columns.Add("groups");
DirectoryEntry rootDSE = null;
假設我想從我處OU提取記錄取出組。現在的路徑是這樣的
部 - >>用戶
和DC這裏是域控制器的名字,對我來說,這是Corp.Local
這樣就可以從您的公司獲取羣組
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;
我懷疑這個線程(http://stackoverflow.com/questions/2188954/see-if-user-is-part-of-active-directory-group-in-c-sharp-asp-net )會很有用,但我不知道如何將代碼合併到我的應用程序中... –
是否要添加新組並將人員添加到組中? – RL89
不,我想使用公司現有的Active Directory組! –