How do I get the current username in .NET using C#?
I tried several combinations from existing answers, but they were giving me
DefaultAppPool
IIS APPPOOL
IIS APPPOOL\DefaultAppPool
I ended up using
string vUserName = User.Identity.Name;
Which gave me the actual users domain username only.
I totally second the other answers, but I would like to highlight one more method which says
String UserName = Request.LogonUserIdentity.Name;
The above method returned me the username in the format: DomainName\UserName. For example, EUROPE\UserName
Which is different from:
String UserName = Environment.UserName;
Which displayed in the format: UserName
And finally:
String UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
which gave: NT AUTHORITY\IUSR
(while running the application on IIS server) and DomainName\UserName
(while running the application on a local server).
Here is the code (but not in C#):
Private m_CurUser As String
Public ReadOnly Property CurrentUser As String
Get
If String.IsNullOrEmpty(m_CurUser) Then
Dim who As System.Security.Principal.IIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
If who Is Nothing Then
m_CurUser = Environment.UserDomainName & "\" & Environment.UserName
Else
m_CurUser = who.Name
End If
End If
Return m_CurUser
End Get
End Property
Here is the code (now also in C#):
private string m_CurUser;
public string CurrentUser
{
get
{
if(string.IsNullOrEmpty(m_CurUser))
{
var who = System.Security.Principal.WindowsIdentity.GetCurrent();
if (who == null)
m_CurUser = System.Environment.UserDomainName + @"\" + System.Environment.UserName;
else
m_CurUser = who.Name;
}
return m_CurUser;
}
}
Use System.Windows.Forms.SystemInformation.UserName
for the actually logged in user as Environment.UserName
still returns the account being used by the current process.
The documentation for Environment.UserName seems to be a bit conflicting:
Environment.UserName Property
On the same page it says:
Gets the user name of the person who is currently logged on to the Windows operating system.
AND
displays the user name of the person who started the current thread
If you test Environment.UserName using RunAs, it will give you the RunAs user account name, not the user originally logged on to Windows.
try this
ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();
string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];
now it looks better