How to Get User Name, Domain Name, Computer Name in .NET

.Net has a nice support for these things, examples are in C# but VB Net translation is obvious, let’s see it:

User Name

The simplest way to retrieve username in .NET is to use System.Environment namespace:

string sUserName;
sUserName = System.Environment.UserName();

Note that user name retrieved is the user that launch process.

Domain Name

Again with System.Environment namespace:

string sUserDomainName;
sUserDomainName = System.Environment.UserDomainName();

Note that this domain name retrieved is the domain of user that launch process.

Computer Name

There are may ways, with System.Environment namespace:

string sMachineName;
sMachineName = System.Environment.MachineName();

But we also use System.Net.Dns namespace and retrieve computer name from DNS in may ways:

string sComputerName;
sComputerName = System.Net.Dns.GetHostName();
string sComputerName;
sComputerName = System.Net.Dns.GetHostByName("localhost").HostName;

Of course your network services must be active to call System.Net.Dns namespace.

VN:F [1.9.15_1155]
Rating: 0.0/10 (0 votes cast)
VN:F [1.9.15_1155]
Rating: 0 (from 0 votes)

Leave a Reply