我的目的是在控制台C#应用程序中连接到Active Directory(在虚拟机上运行(Win SRV 2008R2))并记下域中的所有用户名。因为我是AD的新手,所以我只是设置了连接。
现在第一件事是第一件事;
Root DomainName = frt.local
IP:192.168.x.x
用户名:admin
通过:yyyy我已经编写了下面的代码来设置连接但是会出错。请告诉我我错过的一点。
DirectoryEntry entry = new DirectoryEntry();
entry.Path = "LDAP://192.168.x.x/dc=frt.local";
entry.Username = @"frt.local\admin";
entry.Password = "yyyy";
在指出我错过的任何帮助后,欢迎将用户名写入控制台。
亲切的问候
答案 0 :(得分: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();
}
}
答案 1 :(得分: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
的相当混乱的代码......