How do I get the current username in .NET using C#?
18 Answers
string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;
-
107
-
64@SimonGillbee, this is wrong,
Environment.UserName
will return "RunAs" user.– BoluApr 2, 2014 at 14:45 -
6To verify....
MessageBox.Show(Environment.UserName);
put this in yourwindow_loaded
event, and run it using RunAs....– BoluApr 2, 2014 at 17:05 -
6
-
9This returns
Domain\Username
. How can I get the Name associated with the username? Jun 25, 2015 at 15:23
If you are in a network of users, then the username will be different:
Environment.UserName
- Will Display format : 'Username'
rather than
System.Security.Principal.WindowsIdentity.GetCurrent().Name
- Will Display format : 'NetworkName\Username'
Choose the format you want.
-
10You can use
Environment.UserDomainName + "\\" + Environment.UserName
to get seemingly the same result asSystem.Security.Principal.WindowsIdentity.GetCurrent().Name
. Now, what's the difference, you ask...I am not sure. Oct 6, 2014 at 16:06 -
11I needed to get the user running the app rather than who is logged in (Environment.UserName isn't what I want), so I did the following to strip off the domain:
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split( '\\' ).Last();
– thehelixJan 21, 2015 at 20:54 -
-
1@codenamezero No
ToArray()
is needed. You would needusing System.Linq;
though. Jan 3, 2019 at 15:50 -
2Or without using Linq:
System.Security.Principal.WindowsIdentity.GetCurrent().Name.Split( '\\' )[1];
. Jan 30, 2021 at 1:42
Try the property: Environment.UserName
.
-
5
-
12Caution: like Simon Gillbee mentioned in the comments of the accepted answer,
Environment.UsernName
gives the logged-in account-name, butWindowsIdentity.GetCurrent().Name
is returning the account-name that the application is running as.– GerwaldOct 14, 2014 at 16:00 -
5@leo: Caution: That information is also apparently incorrect, see Bolu's reply. :-) Nov 5, 2015 at 16:56
-
1DO NOT use it with ASP.NET. learn.microsoft.com says: "If an ASP.NET application runs in a development environment, the UserName property returns the name of the current user. In a published ASP.NET application, this property returns the name of the application pool account (such as Default AppPool)."– feihoaOct 22, 2019 at 10:56
The documentation for Environment.UserName seems to be a bit conflicting:
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.
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).
-
-
2@TK-421
Request
only works if you are a web application. It's an instance ofSystem.Web.HttpRequest
Feb 26, 2020 at 12:44 -
@GerardoGrignoli - Thanks for your comment, yes Request would only work if you are using a web application. Dec 7, 2020 at 7:59
-
Any answer that just throws a type name at you without mentioning AT THE VERY LEAST the namespace (not to mention the full name of the assembly) should really be downvoted. Unfortunately, if we were to be doing this, we would have to be downvoting 99% of all C# answers. Oh, humans. Aug 25, 2021 at 11:50
Use:
System.Security.Principal.WindowsIdentity.GetCurrent().Name
That will be the logon name.
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
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.
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.
-
Excellent. I also received the app pool identity only. But your code resolved my problem. Thank you so much. Oct 30, 2014 at 11:47
-
1It sounds like you wanted the username of the user making a request, I guess to an MVC or Web API controller. That's different to the username the process is running under Mar 30, 2016 at 8:30
-
@BenAaronson The question doesn't say anything about what username is running a process. I needed the currently logged in domain username and a search brought me to this page, this code ended up giving me what I needed. Apr 28, 2016 at 12:53
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.
-
Thank you for sharing, also see: System.Windows.Forms.SystemInformation.UserDomainName Feb 16, 2017 at 13:49
I've tried all the previous answers and found the answer on MSDN after none of these worked for me. See 'UserName4' for the correct one for me.
I'm after the Logged in User, as displayed by:
<asp:LoginName ID="LoginName1" runat="server" />
Here's a little function I wrote to try them all. My result is in the comments after each row.
protected string GetLoggedInUsername()
{
string UserName = System.Security.Principal.WindowsIdentity.GetCurrent().Name; // Gives NT AUTHORITY\SYSTEM
String UserName2 = Request.LogonUserIdentity.Name; // Gives NT AUTHORITY\SYSTEM
String UserName3 = Environment.UserName; // Gives SYSTEM
string UserName4 = HttpContext.Current.User.Identity.Name; // Gives actual user logged on (as seen in <ASP:Login />)
string UserName5 = System.Windows.Forms.SystemInformation.UserName; // Gives SYSTEM
return UserName4;
}
Calling this function returns the logged in username by return.
Update: I would like to point out that running this code on my Local server instance shows me that Username4 returns "" (an empty string), but UserName3 and UserName5 return the logged in User. Just something to beware of.
-
My website is using IIS but when I visit the page from another computer within the network, I keep seeing "Network Service" as the username. I tried all different option but it doesn't give me the logged in user who is viewing the page. Any idea?– Si8Aug 8, 2016 at 16:53
-
3NOTE: It's not made clear, but the above example applies in the context of a web application running in IIS, where several of them will display the name of the server windows account that executes the ASP.Net application pool. If running as a interactive program or windows service, the one from HttpContext will be unavailable, and one of the others should be used to find the account under which the process executes. Jun 6, 2017 at 13:54
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
-
1Thanks for this example. Note that this is different from the above answers, but exactly what I was looking for. This code returns the logged user EVEN IF THE PROCESS WAS ELEVATED and now runs in admin name. I needed this for my Setup.exe. If I run the Setup.exe on a non-user account the Windows Installer asks for the password of an administrator account. Then the setup runs in the username of the admin. 'Environment.UserName' as well as 'System.Windows.Forms.SystemInformation.UserName' as well as 'System.Security.Principal.WindowsIdentity.GetCurrent().Name' return the admin user but not this. May 28, 2022 at 7:25
-
Just be aware that in case of no logged in user this code will produce an exception May 28, 2022 at 7:26
-
BE CAREFUL - This answer uses Windows Management Instrumentation (WMI), which is the infrastructure for managing Windows-based operating systems. I used this in our app, and we got a number of failures in the field, caused either by users having a corrupt WMI database on their machine, or the WMI service not running at all. There are usually less-expensive, more reliable ways to do things if you're already running on the local machine. yesterday
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;
}
}
For a Windows Forms app that was to be distributed to several users, many of which log in over vpn, I had tried several ways which all worked for my local machine testing but not for others. I came across a Microsoft article that I adapted and works.
using System;
using System.Security.Principal;
namespace ManageExclusion
{
public static class UserIdentity
{
// concept borrowed from
// https://msdn.microsoft.com/en-us/library/system.security.principal.windowsidentity(v=vs.110).aspx
public static string GetUser()
{
IntPtr accountToken = WindowsIdentity.GetCurrent().Token;
WindowsIdentity windowsIdentity = new WindowsIdentity(accountToken);
return windowsIdentity.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);
}
}
-
My website is using IIS but when I visit the page from another computer within the network, I keep seeing "Network Service" as the username. I tried all different option but it doesn't give me the logged in user who is viewing the page. Any idea?– Si8Aug 8, 2016 at 16:53
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.
-
3I've flagged this as "not an answer" because it starts off talking about a completely unrelated exception caused by you blindly trying to substring(4) a string that clearly doesn't have at least 4 characters in it, which is nothing to do with the question, and then only mentions solutions that have already been mentioned many times before in other answers. This answer is just noise and should be deleted Mar 5, 2021 at 6:59
I went over most of the answers here and none of them gave me the right user name.
In my case I wanted to get the logged in user name, while running my app from a different user, like when shift+right click on a file and "Run as a different user".
The answers I tried gave me the 'other' username.
This blog post supplies a way to get the logged in user name, which works even in my scenario:
https://smbadiwe.github.io/post/track-activities-windows-service/
It uses Wtsapi
Edit: the essential code from the blog post, in case it ever disappears, is
Add this code to a class inheriting from ServiceBase
[DllImport("Wtsapi32.dll")]
private static extern bool WTSQuerySessionInformation(IntPtr hServer, int sessionId, WtsInfoClass wtsInfoClass, out IntPtr ppBuffer, out int pBytesReturned);
[DllImport("Wtsapi32.dll")]
private static extern void WTSFreeMemory(IntPtr pointer);
private enum WtsInfoClass
{
WTSUserName = 5,
WTSDomainName = 7,
}
private static string GetUsername(int sessionId, bool prependDomain = true)
{
IntPtr buffer;
int strLen;
string username = "SYSTEM";
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSUserName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer);
WTSFreeMemory(buffer);
if (prependDomain)
{
if (WTSQuerySessionInformation(IntPtr.Zero, sessionId, WtsInfoClass.WTSDomainName, out buffer, out strLen) && strLen > 1)
{
username = Marshal.PtrToStringAnsi(buffer) + "\\" + username;
WTSFreeMemory(buffer);
}
}
}
return username;
}
If you don't have one already, add a constructor to the class; and add this line to it:
CanHandleSessionChangeEvent = true;
EDIT: Per comments requests, here's how I get the session ID - which is the active console session ID:
[DllImport("kernel32.dll")]
private static extern uint WTSGetActiveConsoleSessionId();
var activeSessionId = WTSGetActiveConsoleSessionId();
if (activeSessionId == INVALID_SESSION_ID) //failed
{
logger.WriteLog("No session attached to console!");
}
-
1Always copy external content into your answer rather than just putting a link. If the link dies your answer is useless Mar 5, 2021 at 6:55
-
-
-
This route is not reliable. Depending on where the app is. If it runs in a secure network, like a hospital, odds are this will fail. I've seen it happen in a terminal environment before. The accepted answer works just fine. Aug 31, 2022 at 21:17
-
Ok, but fact is that for my use case, which is described in the answer I posted, the accepted answer does not work, and my answer does.– Alonzzo2Sep 2, 2022 at 6:32