C# LDAP连接到AD并搜索所有OU中的所有用户
我使用代码:从我的广告中获取所有用户 现在,我正在尝试通过LDAP连接到域,以便通过以下更改从该Active Directory获取所有用户:C# LDAP连接到AD并搜索所有OU中的所有用户,c#,active-directory,ldap,C#,Active Directory,Ldap,我使用代码:从我的广告中获取所有用户 现在,我正在尝试通过LDAP连接到域,以便通过以下更改从该Active Directory获取所有用户: using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "192.168.1.100", "Username@testdomain.local", "Password")) testdomain.local上有两个不同的OU和用户,但我只得到一个OU的用户?
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "192.168.1.100", "Username@testdomain.local", "Password"))
testdomain.local上有两个不同的OU和用户,但我只得到一个OU的用户?
我想这会给我所有的用户从所有我们从广告
如果我对我当前的广告域使用以下内容,那么我从所有OU获得所有用户
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, currentDomain))
这可能是另一个域上的配置问题,还是该代码不适用于LDAP连接
多谢各位
更新:
代码:
using (PrincipalContext context = new PrincipalContext(ContextType.Domain, "192.168.1.100", "Username@testdomain.local", "Password"))
{
using (PrincipalSearcher searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
de.Properties["samAccountName"].Value
}
catch (Exception c)
{
}
result.Dispose();
}
}
您上面的代码工作正常,可以提取所有记录,没有任何错误或跳过。我建议将域名从IP地址更改为
testdomain.local
,用户名不带@testdomain.local
如果您希望获取samAccountName或其他属性,并将其转换为DirectoryEntry,我建议使用以下使用DirectorySearcher的方法。它提供了更好的性能并在所有OU中查找
DirectoryEntry entry = new DirectoryEntry("LDAP://DC=testdomain,DC=local", "username", "password");
string searchQuery = $"(&(objectCategory=user)(objectClass=user))";
var listOfUsers = new List<string>();
DirectorySearcher ds = new DirectorySearcher(entry, searchQuery,
new string[] { "samAccountName" });
ds.SizeLimit = int.MaxValue;
ds.PageSize = int.MaxValue;
foreach (SearchResult user in ds.FindAll())
{
string samAccountName = user.Properties["samAccountName"][0].ToString();
Console.WriteLine(samAccountName);
listOfUsers.Add(samAccountName);
}
DirectoryEntry=newdirectoryEntry(“LDAP://DC=testdomain,DC=local”,“用户名”,“密码”);
字符串searchQuery=$”(&(objectCategory=user)(objectClass=user))”;
var listOfUsers=新列表();
DirectorySearcher ds=新的DirectorySearcher(条目、搜索查询、,
新字符串[]{“samAccountName”});
ds.SizeLimit=int.MaxValue;
ds.PageSize=int.MaxValue;
foreach(ds.FindAll()中的SearchResult用户)
{
字符串samAccountName=user.Properties[“samAccountName”][0].ToString();
Console.WriteLine(samAccountName);
添加(samAccountName);
}
您只显示定义正在使用的域/上下文的脚本。。不是您正在运行的将结果限制为一个OU的查询。如果您使用的是PrincipalSearcher,它将查找所有帐户,不限制结果或OU的数量。嗨,Jawad,这是链接帖子中的代码,我更新了我的帖子。谢谢谢谢你的建议,我会看一看,也许会看一下代码。如果我对你的理解是正确的,那么就没有必要使用Principalsearcher或PrincipalContext?我读到,主要搜索者应该比直接搜索者更快?我会查一查。谢谢,我绝对建议你测试一下。在我所做的所有测试中,DirectorySearcher比PrincipalSearcher快得多。在这里有一个很好的阅读关于性能的另一个与一些速度措施。非常感谢。