BlackWaspTM

This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Security
.NET 2.0+

Get the Current User's Login Name

Modern secure software requires either a login name and password, or detects the current user and automatically assigns the correct permissions. In order to create a security system that requires no password, the current user must be identified.

System.Security.Principal Namespace

The System.Security.Principal namespace is used to access security information related to Windows users and groups. One of the classes within this namespace is the WindowsIdentity class that is used to represent a single Windows user. Using this object we can retrieve the current user's identity information using the static GetCurrent method. NB: Remember to add using System.Security.Principal; at the top of your code to use the examples below.

WindowsIdentity id = WindowsIdentity.GetCurrent();

The WindowsIdentity object that we have now retrieved holds various data relating to the current user. To retrieve the login name, including the machine or domain name, simply read the Name property.

WindowsIdentity id = WindowsIdentity.GetCurrent();
string login = id.Name;
Console.WriteLine(login);      // Outputs "BLACKWASP\Administrator" (or similar)

In the above example, the returned value includes the domain name preceding the backwards slash character and the user name following the backslash. These could now be easily separated using standard string manipulation features.

25 August 2007