通过.net获取Active Directory组中的用户名

Eri*_*ric 13 .net c# active-directory visual-studio-2010

下面的代码获取组中的用户但返回了它 "CN=johnson\,Tom,OU=Users,OU=Main,DC=company,DC=com"

我想只返回名字和姓氏.我怎么能做到这一点?

DirectoryEntry ou = new DirectoryEntry();
DirectorySearcher src = new DirectorySearcher();

src.Filter = ("(&(objectClass=group)(CN=Gname))");
SearchResult res = src.FindOne();
if (res != null)
{
    DirectoryEntry deGroup = new DirectoryEntry(res.Path);
    PropertyCollection pcoll = deGroup.Properties;

    foreach (object obj in deGroup.Properties["member"])
    {
            ListBox1.Items.Add(obj.ToString());
    }
}
Run Code Online (Sandbox Code Playgroud)

Rus*_*ure 34

我更喜欢使用System.DirectoryServices.AccountManagement中的类:

PrincipalContext principalContext = new PrincipalContext(ContextType.Domain);
GroupPrincipal group = GroupPrincipal.FindByIdentity(principalContext, "GName");
Run Code Online (Sandbox Code Playgroud)

搜索group.Members属性,直到您拥有所需的Principal.然后像这样提取名称:

foreach (Principal principal in group.Members)
{
   string name = principal.Name;
}
Run Code Online (Sandbox Code Playgroud)

  • 您需要在项目中添加对**System.DirectoryServices.AccountManagement**的引用. (4认同)