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

System Information
.NET 1.1+

Obtaining the User's Domain and User Name

There are several ways in which the login details of the current can be obtained in .NET applications. This article describes two properties of the Environment class, which return the user's name and the name of the user's domain.

Environment Class

The Environment class is useful when you wish to obtain or manipulate details of the current operating environment. It includes many static members that return information about the executing program or assembly, the user and the operating system settings. Some of the class's properties are writeable, allowing you to modify the values of items such as the current working directory. The class also includes methods for similar, usually more complex or slower, operations.

UserName and UserDomainName

Often you will want to obtain the login details for the current user. For example, you might create software that users can customise to their own preferences. To avoid one user's options being applied for another, you can link settings to a user's domain and user name. You can then identify the user when your application loads and apply the correct customisations accordingly. This is particularly useful when many users share a computer or when preferences are stored centrally so that they follow a user that has access to more than one machine.

In an earlier article I explained how the domain name and user name can be obtained in a single string, using the WindowsIdentity class. Another option is to read two static properties of the Environment class. These are UserName and UserDomainName.

UserName returns a string that contains the user's name, not including the domain name for networked accounts or the machine name for local ones. It returns user details for the current thread. UserDomainName returns the current user's domain name for Active Directory accounts or the machine name for local accounts.

Console.WriteLine("{0}\\{1}", Environment.UserDomainName, Environment.UserName);



23 February 2014