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;
}
Comments
-
MBZ almost 2 years
How can I get a list of local computer usernames in windows using C#?
-
MBZ over 13 yearsthese would return the Current username. I want all of them.
-
MBZ over 13 yearstnx, but doesn't seem very standard! :D
-
Roger Lipscombe over 13 years...it also assumes that they've ever logged in.
-
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 over 6 yearsWarning: 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 over 4 yearsIs there a way in C# to get only the users who have ever logged in?
-
Juan Rojas over 4 yearsThis answer shows the users who are logged in my windows using interop stackoverflow.com/a/132774/403999
-
marsh-wiggle about 4 yearsGreat! Have you tested it when the machine is no directory member?
-
VansFannel about 4 years@marsh-wiggle No, sorry.
-
jjxtra over 2 yearsIs there any way to do this without wmi?
-
Sebastian Krysmanski about 2 yearsNote 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 theSelectQuery
constructor to get only the local users.