[英]Get all the user's groups from active directory in C#
I'm trying to get all the user's groups in the active directory with c# code. 我正在尝试使用c#代码获取活动目录中的所有用户组。
This is my code: 这是我的代码:
private List<GroupPrincipal> GetGroups()
{
string userName = User.Identity.Name;
string host = Request.Url.Host.ToLower();
List<GroupPrincipal> result = new List<GroupPrincipal>();
UserPrincipal user = UserPrincipal.FindByIdentity(new PrincipalContext(ContextType.Domain, host), IdentityType.SamAccountName, userName);
foreach (GroupPrincipal group in user.GetGroups())
{
result.Add(group);
}
return result;
}
I receive an error on the row that starts with UserPrincipal user that says that the server could not be connected. 我在以UserPrincipal用户开头的行上收到错误消息,提示无法连接服务器。 I'm running my code from the server itself so I can connect it.
我正在从服务器本身运行代码,因此可以连接它。
What am i doing wrong? 我究竟做错了什么?
Thank you in advance! 先感谢您!
To connect with Active Directory, Create PrincipalContext object. 要连接Active Directory,请创建PrincipalContext对象。
PrincipalContext insPrincipalContext = new PrincipalContext(ContextType.Domain, "MyDomain",
"DC=MyDomain,DC=com");
Code to get all Groups: Create GroupPrincipal object and call SearchGroups() which returns list of all groups of given domain. 获取所有组的代码:创建GroupPrincipal对象并调用SearchGroups(),它返回给定域的所有组的列表。
private void ListGroups(){
GroupPrincipal insGroupPrincipal = new GroupPrincipal(insPrincipalContext);
insGroupPrincipal.Name = "*";
SearchGroups(insGroupPrincipal);}
private void SearchGroups(GroupPrincipal parGroupPrincipal)
{
List<Principal> oList = new List<Principal>();
PrincipalSearcher insPrincipalSearcher = new PrincipalSearcher();
insPrincipalSearcher.QueryFilter = parGroupPrincipal;
PrincipalSearchResult<Principal> results = insPrincipalSearcher.FindAll();
foreach (Principal p in results)
{
oList.Add(p);
}
}
This link will also help you - http://www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement 此链接也将为您提供帮助-http: //www.codeproject.com/Articles/38344/Using-System-DirectoryServices-AccountManagement
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.