Hi guys, how can we query the NT/Users database for all users on the machine?
+3
A:
You can use the System.DirectoryServices namespace to do this. Here's an excellent article depicting how to use the classes of that namespace.
Here's the code showing how to do it:
DirectoryEntry entry = new DirectoryEntry("WinNT://MACHINE_NAME");
entry.AuthenticationType = AuthenticationTypes.Secure;
DirectorySearcher deSearch = new DirectorySearcher(entry);
deSearch.Filter = "(&(objectClass=user))";
SearchResultCollection results = deSearch.FindAll();
foreach (SearchResult srUser in results)
{
try
{
DirectoryEntry de = srUser.GetDirectoryEntry();
lstbox.Items.Add(de.Properties["sAMAccountName"].Value.ToString());
}
catch { }
}
Kirtan
2009-05-26 11:11:11
In order to get the local users, you would have to write "WinNT://MACHINE_NAME" instead of "LDAP://MYDOMAIN"
kay.herzam
2009-05-26 11:13:49
Thanks, Kay. Updated the answer.
Kirtan
2009-05-26 11:26:14
+2
A:
I assume you're using C#. You can get them using WMI:
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();
}
}
}
kay.herzam
2009-05-26 11:11:39