Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get windows users with C#

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

like image 292
Elmex Avatar asked May 17 '11 15:05

Elmex


People also ask

How do I get the current user in Windows?

In the box, type cmd and press Enter. The command prompt window will appear. Type whoami and press Enter. Your current user name will be displayed.

How do I get the current username in .NET using C#?

GetCurrent(). Name; Returns: NetworkName\Username. Gets the user's Windows logon name.

How do I see all users on my network?

Open Computer Management, and go to “Local Users and Groups -> Users.” On the right side, you get to see all the user accounts, their names as used by Windows behind the scenes, their full names (or the display names), and, in some cases, also a description.


1 Answers

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.

like image 85
IAmTimCorey Avatar answered Oct 27 '22 03:10

IAmTimCorey