【问题标题】:Active Directory Connection C#活动目录连接 C#
【发布时间】:2012-10-17 21:02:22
【问题描述】:

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

现在第一件事就是第一;

根域名 = frt.local

IP:192.168.x.x

用户名:管理员

通过:yyyy

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

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

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

亲切的问候

【问题讨论】:

  • 我看到您之前已经问过 4 个问题,但没有接受其中任何一个的答案。尝试提高你的回答率,它会鼓励用户回答。
  • 另外,可能值得在问题正文中发布您遇到的例外情况。
  • @Tariqulazam 感谢您的建议。我实际上不熟悉如何使用该网站。
  • 您已经接受了一份。所以你已经在路上了。现在正如 Jonners 建议的那样,您能否更新您的问题以包含您遇到的异常?
  • 当我回到办公室时我会的,保证:)

标签: c# .net active-directory connection-string


【解决方案1】:

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 的相当混乱的代码...

【讨论】:

    【解决方案2】:
      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();
        }
      }
    

    【讨论】:

    • 查看我的回复 - 不太清楚你为什么使用返回 PrincipalPrincipalSearcher - 但是你去获取底层的 DirectoryEntry 并拥有所有杂乱的代码来访问它的属性。 ...更好地使用您已经从 PrincipalSearcher 返回的 UserPrincipal 对象!
    猜你喜欢
    • 1970-01-01
    • 2012-03-05
    • 2016-08-05
    • 1970-01-01
    • 2019-04-02
    • 2020-06-04
    • 2019-05-20
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多