Get windows users with C#

Elmex picture Elmex · May 17, 2011 · Viewed 11k times · Source

How can I get a list of all windows users of the local machine with the usage of .NET (C#) ?

Answer

IAmTimCorey picture IAmTimCorey · May 17, 2011

Here is a blog post (with code) that explains how to do it:

http://csharptuning.blogspot.com/2007/09/how-to-get-list-of-windows-user-in-c.html

The author lists the following code (quoted from the above site):

DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("users","group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
    DirectoryEntry member = new DirectoryEntry(groupMember);
    lstUsers.Items.Add(member.Name);
}

You need to add using System.DirectoryServices at the top of your code. To change machines, you would change the Environment.MachineName to be whatever machine you want to access (as long as you have permission to do so and the firewall isn't blocking you from doing so). I also modified the author's code to look at the users group instead of the administrators group.