在C#中,如何访问Active Directory,以获得一定的用户属于该组的列表? [英] In C#, how to access Active Directory to get the list of groups that a certain user belongs to?
本文介绍了在C#中,如何访问Active Directory,以获得一定的用户属于该组的列表?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C#中,我如何访问Active Directory来获得团体,某用户所属的列表?
In C#, how do i access Active Directory to get the list of groups that a certain user belongs to?
用户详细信息的形式为:
The user details are in the form:
"MYDOMAIN\myuser"
我一直在关注指令从这里但他们只有工作,如果我在的形式向用户详细信息:
I've been following the instructions from here but they only work if i have the user details in the form:
"LDAP://sample.com/CN=MySurname MyFirstname,OU=General,OU=Accounts,DC=sample,DC=com"
所以,也许我问的是,如何从第一,短,形式得到下面的完全限定形式?
So maybe what i'm asking is, how to get from the first, shorter, form to the fully qualified form below?
非常感谢!
推荐答案
这可能会帮助...
using System.Collections;
using System.DirectoryServices;
/// <summary>
/// Gets the list of AD groups that a user belongs to
/// </summary>
/// <param name="loginName">The login name of the user (domain\login or login)</param>
/// <returns>A comma delimited list of the user's AD groups</returns>
public static SortedList GetADGroups(string loginName)
{
if (string.IsNullOrEmpty(loginName))
throw new ArgumentException("The loginName should not be empty");
SortedList ADGroups = new SortedList();
int backSlash = loginName.IndexOf("\\");
string userName = backSlash > 0 ? loginName.Substring(backSlash + 1) : loginName;
DirectoryEntry directoryEntry = new DirectoryEntry();
DirectorySearcher directorySearcher = new DirectorySearcher(directoryEntry, "(sAMAccountName=" + userName + ")");
SearchResult searchResult = directorySearcher.FindOne();
if (null != searchResult)
{
DirectoryEntry userADEntry = new DirectoryEntry(searchResult.Path);
// Invoke Groups method.
object userADGroups = userADEntry.Invoke("Groups");
foreach (object obj in (IEnumerable)userADGroups)
{
// Create object for each group.
DirectoryEntry groupDirectoryEntry = new DirectoryEntry(obj);
string groupName = groupDirectoryEntry.Name.Replace("cn=", string.Empty);
groupName = groupName.Replace("CN=", string.Empty);
if (!ADGroups.ContainsKey(groupName))
ADGroups.Add(groupName, groupName);
}
}
return ADGroups;
}
这篇关于在C#中,如何访问Active Directory,以获得一定的用户属于该组的列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文