How can I get a list of local computer usernames in windows using C#?
Asked
Active
Viewed 2.6k times
4 Answers
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
-
2Warning: 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
-
Great! Have you tested it when the machine is no directory member? – marsh-wiggle Apr 15 '20 at 07:58
-
-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
-
1
-
3
-
Is there a way in C# to get only the users who have ever logged in? – Juan Rojas Jan 23 '20 at 23:46
-
This answer shows the users who are logged in my windows using interop https://stackoverflow.com/a/132774/403999 – Juan Rojas Jan 24 '20 at 00:42
-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