Get list of local computer usernames in Windows

Solution 1:

using System.Management;

SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
     Console.WriteLine("Username : {0}", envVar["Name"]);
}

This code is the same as the link KeithS posted. I used it a couple years ago without issue but had forgotten where it came from, thanks Keith.

Solution 2:

I use this code to get my local Windows 7 users:

public static List<string> GetComputerUsers()
{
    List<string> users = new List<string>();
    var path =
        string.Format("WinNT://{0},computer", Environment.MachineName);

    using (var computerEntry = new DirectoryEntry(path))
        foreach (DirectoryEntry childEntry in computerEntry.Children)
            if (childEntry.SchemaClassName == "User")
                users.Add(childEntry.Name);

    return users;
}