There is more than one way to get the current username using C# or VB.NET i will show you one using Environment Variable and one using the WindowsIdentity.

If you are in a Network the output of both methods is different.

 

using the Environment variable

 

Sample C#

string currUsername = Environment.UserName;

 

Sample VB.NET

Dim currUsername As String = Environment.UserName

using the WindowsIdentity

 

Sample C#

string currUsername = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

 

Sample VB.NET

Dim currUsername As String = System.Security.Principal.WindowsIdentity.GetCurrent().Name

 

Possible Output

using the Environment Variable: Username
using the WindowsIdentity: Domainname\Username

Tip
if you want to use the Environment variables and want to get the Domainname also, take a look at Environment.UserDomainName Property

for more informations take a look at the MSDN: Environment.UserName, WindowsIdentity Class

One thought on “How to get the current username using C# or VB.NET”

Leave a Reply