如何在 .NET 中搜索域中的所有用户帐户?
不是域中的计算机名称,而是用户帐户,这就是您用于登录 Windows 的内容。
您可以尝试以下方法。
PrincipalContext ctx = new PrincipalContext(ContextType.Machine,Environment.MachineName);
UserPrincipal user = new UserPrincipal(ctx);
user.Name = "*";
PrincipalSearcher ps = new PrincipalSearcher();
ps.QueryFilter = user;
PrincipalSearchResult<Principal> result = ps.FindAll();
foreach (Principal p in result)
{
using (UserPrincipal up = (UserPrincipal)p)
{
MessageBox.Show(up.Name);
}
}
或这个:
using System.Management;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
Console.WriteLine("Username : {0}", envVar["Name"]);
}
Console.ReadLine();
}
另请参阅如何列出所有 Windows 用户。
搜索域用户的另一种方法:
using System.DirectoryServices;
using System.DirectoryServices.ActiveDirectory;
using (var domain = Domain.GetCurrentDomain())
using (var directoryEntry = domain.GetDirectoryEntry())
using (var directorySearcher = new DirectorySearcher(directoryEntry, "(&(objectCategory=person)(objectClass=user))"))
{
directorySearcher.PageSize = 1000;
using (var searchResults = directorySearcher.FindAll())
{
foreach (SearchResult searchResult in searchResults)
{
using (var userEntry = searchResult.GetDirectoryEntry())
{
Console.WriteLine(userEntry.Properties["cn"][0]);
}
}
}
}
您可以使用以下内容:
List<string> LdapUsers = new List<string>();
if (String.IsNullOrWhiteSpace(domain))
{
string username = WindowsIdentity.GetCurrent().Name;
domain = username.Substring(0, username.IndexOf("\\"));
}
PrincipalContext context;
if (!String.IsNullOrWhiteSpace(user) && !String.IsNullOrWhiteSpace(password) && !String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain, user, password);
if (!String.IsNullOrWhiteSpace(domain))
context = new PrincipalContext(ContextType.Domain, domain);
else
context = new PrincipalContext(ContextType.Domain);
UserPrincipal userP = new UserPrincipal(context);
userP.Enabled = true;
PrincipalSearcher pS = new PrincipalSearcher();
pS.QueryFilter = userP;
PrincipalSearchResult<Principal> result = pS.FindAll();
foreach (Principal p in result)
LdapUsers.Add(domain + "\\" + p.SamAccountName);