简体   繁体   English

在 C# 中获取 Active Directory 组的用户名

[英]Get user names of Active Directory group in c#

I need to get user details of a particular Active Directory group.我需要获取特定 Active Directory 组的用户详细信息。 I am using this code:我正在使用此代码:

var result = grpResponse.Entries[0];

if (result.Attributes["member"] != null)
{
    for (var i = 0; i < result.Attributes["member"].Count; i++)
    {
          var filter = result.Attributes["member"][i].ToString();

          var query = "(&(objectClass=user)(" + filter + "))"; // Here I need username to use like cn=username

          var userRequest = new SearchRequest(distinguishedName, query,
                                    SearchScope.Subtree);

In filter I am getting something like在过滤器中,我得到了类似的东西

CN=Name,OU=something,DC=example

How can I take this cn value ie user name alone?我怎样才能单独使用这个 cn 值,即用户名?

If you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement (S.DS.AM) namespace.如果您使用 .NET 3.5 及更高版本,则应查看System.DirectoryServices.AccountManagement (S.DS.AM) 命名空间。

Basically, you can define a domain context and easily find users and/or groups in AD:基本上,您可以定义域上下文并轻松找到 AD 中的用户和/或组:

// set up domain context - limit to the OU you're interested in
using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, "OU=YourOU,DC=YourCompany,DC=Com"))
{
    // find the group in question
    GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");

    // if found....
    if (group != null)
    {
       // iterate over the group's members
       foreach (Principal p in group.GetMembers())
       {
           Console.WriteLine("{0}: {1}", p.StructuralObjectClass, p.DisplayName);

           // do whatever else you need to do to those members
       }
    }
}

The new S.DS.AM makes it really easy to play around with users and groups in AD!新的 S.DS.AM 使在 AD 中与用户和组一起玩变得非常容易!

Read more about it here:在此处阅读更多相关信息:

The below is exactly what I needed.下面正是我需要的。

The OuString you use like ours may have has multiple parts - both OU & DC您像我们一样使用的 OuString 可能有多个部分 - OU 和 DC

bstring OUString = "OU=Groups,OU=Accounts,DC=nw,DC=nos,DC=ourcompanyName,DC=com" ;

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, null, OUString))

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM