Get list of local computer usernames in Windows

25,890

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;
}
Share:
25,890
MBZ
Author by

MBZ

PhD Student in Computer Science at UIUC

Updated on July 09, 2022

Comments

  • MBZ
    MBZ almost 2 years

    How can I get a list of local computer usernames in windows using C#?

  • MBZ
    MBZ over 13 years
    these would return the Current username. I want all of them.
  • MBZ
    MBZ over 13 years
    tnx, but doesn't seem very standard! :D
  • Roger Lipscombe
    Roger Lipscombe over 13 years
    ...it also assumes that they've ever logged in.
  • eglasius
    eglasius almost 12 years
    "without issue" -> in my experience WMI has a failure rate > 0.5%, so be careful if integrating in a customer facing app
  • Mike
    Mike over 6 years
    Warning: This command will take a very long time if you are connected to a large network. You can test this command in airplane mode to find the expected results.
  • Juan Rojas
    Juan Rojas over 4 years
    Is there a way in C# to get only the users who have ever logged in?
  • Juan Rojas
    Juan Rojas over 4 years
    This answer shows the users who are logged in my windows using interop stackoverflow.com/a/132774/403999
  • marsh-wiggle
    marsh-wiggle about 4 years
    Great! Have you tested it when the machine is no directory member?
  • VansFannel
    VansFannel about 4 years
    @marsh-wiggle No, sorry.
  • jjxtra
    jjxtra over 2 years
    Is there any way to do this without wmi?
  • Sebastian Krysmanski
    Sebastian Krysmanski about 2 years
    Note that, if your computer is connected to a AD domain, this could does not return the local users but the users in your domain. You need to add $"domain='{Environment.MachineName}'" as second parameter to the SelectQuery constructor to get only the local users.