How do I get the current username in .NET using C#?
In case it's helpful to others, when I upgraded an app from c#.net 3.5 app to Visual Studio 2017 this line of code User.Identity.Name.Substring(4);
threw this error "startIndex cannot be larger than length of string" (it didn't baulk before).
It was happy when I changed it to System.Security.Principal.WindowsIdentity.GetCurrent().Name
however I ended up using Environment.UserName;
to get the logged in Windows user and without the domain portion.
Just in case someone is looking for user Display Name as opposed to User Name, like me.
Here's the treat :
System.DirectoryServices.AccountManagement.UserPrincipal.Current.DisplayName
Add Reference to System.DirectoryServices.AccountManagement
in your project.
String myUserName = Environment.UserName
This will give you output - your_user_name
Get the current Windows username:
using System;
class Sample
{
public static void Main()
{
Console.WriteLine();
// <-- Keep this information secure! -->
Console.WriteLine("UserName: {0}", Environment.UserName);
}
}
Try the property: Environment.UserName.
You may also want to try using:
Environment.UserName;
Like this...:
string j = "Your WindowsXP Account Name is: " + Environment.UserName;
Hope this has been helpful.