2

我的目的是在控制台 C# 应用程序中连接到 Active Directory(在虚拟机 (Win SRV 2008R2) 上运行)并记下域中的所有用户名。由于我是 AD 的新手,我只是在设置连接时遇到了困难。

现在第一件事就是第一;

根域名 = frt.local

IP : 192.168.xx

用户名:管理员

通行证:yyyy

我编写了下面的代码来设置连接但出现错误。请告诉我我错过的重点。

DirectoryEntry entry = new DirectoryEntry();
entry.Path = "LDAP://192.168.x.x/dc=frt.local";
entry.Username = @"frt.local\admin";
entry.Password = "yyyy";

在指出我错过的任何帮助之后,关于将用户名写到控制台的任何帮助都会受到欢迎。

亲切的问候

4

2 回答 2

3
  var username = "your username";
  var password = "your password";
  var domain = "your domain";
  var ctx = new PrincipalContext(ContextType.Domain, domain, username, password);

  using (var searcher = new PrincipalSearcher(new UserPrincipal(ctx)))
  {
    foreach (var result in searcher.FindAll())
    {
      DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
      Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
      Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
      Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
      Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
      Console.WriteLine();
    }
  }
于 2012-10-17T21:23:32.883 回答
3

Nesim 的回答很好——一开始。但我真的不认为使用它有任何意义或需要

DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;

行 - PrincipalSearcher 的结果已经是 UserPrincpial 并且您可以像这样更轻松地访问它的属性:

using (var searcher = new PrincipalSearcher(new UserPrincipal(ctx)))
{
   foreach (var result in searcher.FindAll())
   {
       UserPrincipal foundUser = result as UserPrincipal;

       if(foundUser != null)
       {
           Console.WriteLine("First Name: {0}", foundUser.GivenName);
           Console.WriteLine("Last Name : {0}", foundUser.Surname);
           Console.WriteLine("SAM account name; {0}", foundUser.SamAccountName);
           Console.WriteLine("User principal name: {0}", foundUser.UserPrincipalName);         
           Console.WriteLine();
       }
   }
}

已经并且非常好地将UserPrincipal最常用的属性公开为对象本身的属性 - 不需要带有DirectoryEntry...的相当混乱的代码

于 2012-10-18T05:08:22.133 回答