20

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

Bobby
  • 11,167
  • 5
  • 43
  • 68
MBZ
  • 24,505
  • 45
  • 111
  • 185

4 Answers4

31
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.

sclarson
  • 4,339
  • 3
  • 33
  • 43
  • "without issue" -> in my experience WMI has a failure rate > 0.5%, so be careful if integrating in a customer facing app – eglasius Aug 10 '12 at 08:43
  • 2
    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. – Mike Oct 10 '17 at 22:30
  • Is there any way to do this without wmi? – jjxtra Jan 09 '22 at 15:59
10

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;
}
VansFannel
  • 43,504
  • 101
  • 342
  • 588
-1

One way would be to list the directories in C:\Documents and Settings (in Vista/7: C:\Users).

yellowblood
  • 1,574
  • 1
  • 15
  • 30
-3

The following are a few different ways to get your local computer name:

string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);
James
  • 651
  • 3
  • 10