本文介绍了在 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?
用户详细信息格式为:
"MYDOMAINmyuser"
我一直在遵循 此处的说明,但它们仅适用如果我在表单中有用户详细信息:
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?
非常感谢!
推荐答案
这可能会有所帮助...
This might help...
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 (domainlogin 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 以获取某个用户所属的组列表?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!
本站部分内容来源互联网,如果有图片或者内容侵犯了您的权益,请联系我们,我们会在确认后第一时间进行删除!