【问题标题】:Get all users in Active Directory group获取 Active Directory 组中的所有用户
【发布时间】:2011-08-31 05:35:41
【问题描述】:

我正在尝试获取属于 Active Directory 中某个组的所有用户。我想将结果显示为下拉菜单供站点用户选择。这是我目前所拥有的:

public IEnumerable<KeyValuePair<string, string>> GetAllMembers(string group)
{
    var domainContext = new PrincipalContext(ContextType.Domain);
    var group = GroupPrincipal.FindByIdentity(domainContext, group);

    return from principal in @group.Members select new KeyValuePair<string, string>(/* need to fill in key and value */);
}

我遇到的问题是我在活动目录之外开发它,所以还不能真正测试它(长话短说不要问)。在将其部署到测试环境时,我希望最大限度地提高成功机会。

我的问题是:如果我希望键值对包含登录用户名(键,例如:"DOMAIN\darkoz")和用户真实姓名(值,例如:"Darko Z"),我该如何获得这些? Principal 对象至少有 5 个属性,其中包含单词 Name,所以我不确定哪个是哪个。

额外问题:这是实现我的目标的普遍接受的方式吗?我意识到这是一个非常简单的问题,但由于我对 Active Directory 缺乏了解,如果有更好的方法来解决这个问题,我不会感到惊讶。这是否可以在非管理员帐户上运行?

【问题讨论】:

  • 即使这不是你真正的问题,也许this 可以给你一些额外的想法。

标签: c# .net asp.net-mvc-3 c#-4.0 .net-4.0


【解决方案1】:

解决方案正如我所怀疑的那样:

public IEnumerable<KeyValuePair<string, string>> GetAllMembers(string group)
{
    var domainContext = new PrincipalContext(ContextType.Domain);
    var groupPrincipal = GroupPrincipal.FindByIdentity(domainContext, IdentityType.SamAccountName, group);

    return from m
           in groupPrincipal.Members 
           select new KeyValuePair<string, string>(m.SamAccountName, m.Name);
}

SamAccountName 提供用户登录名,Name 是实际名称

【讨论】:

    【解决方案2】:

    我会阅读以前的类似问题来回答您的两个问题,关于最佳实践以及如何读取帐户名和全名:Get all users from AD domain

    无论如何,来自 MS 论坛:

    static void Main(string[] args)
    {
        string groupName = "Domain Users";
        string domainName = "";
    
        PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domainName);
        GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, groupName);
    
        if (grp != null)
        {
             foreach (Principal p in grp.GetMembers(false))
                {
                    Console.WriteLine(p.SamAccountName + " - " + p.DisplayName);
                }
    
    
            grp.Dispose();
            ctx.Dispose();
            Console.ReadLine();
        }
        else
        {
            Console.WriteLine("\nWe did not find that group in that domain, perhaps the group resides in a different domain?");
            Console.ReadLine();
        }
    }
    

    来源:Get list of Active Directory users in C#

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-06-02
      • 1970-01-01
      相关资源
      最近更新 更多