- 1 year ago
How to Get the list of all User Accounts of Windows in C#?
To retrieve the list of all user accounts in Windows using C#, you can utilize the System.DirectoryServices.AccountManagement namespace. Here's an example:
csharpusing System;
using System.DirectoryServices.AccountManagement;
class Program
{
static void Main()
{
try
{
using (var context = new PrincipalContext(ContextType.Machine))
{
using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
{
foreach (var result in searcher.FindAll())
{
if (result is UserPrincipal userPrincipal)
{
Console.WriteLine("Username: " + userPrincipal.SamAccountName);
Console.WriteLine("Full Name: " + userPrincipal.DisplayName);
Console.WriteLine();
}
}
}
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
In this example, the PrincipalContext
is created with ContextType.Machine
to target the local machine. You can modify the context type if you want to retrieve user accounts from a specific domain or different context.
The PrincipalSearcher
is initialized with a UserPrincipal
to search for user accounts. The FindAll
method returns a collection of Principal
objects, which are then filtered to retrieve only UserPrincipal
objects.
For each UserPrincipal
found, the sample code prints the username (SamAccountName
) and the full name (DisplayName
).
Compile and run the code, and it will display the list of user accounts on the Windows machine.