Yves
Yves

Reputation: 12507

How do I get the current username in .NET using C#?

How do I get the current username in .NET using C#?

Upvotes: 746

Views: 846173

Answers (17)

juan
juan

Reputation: 81954

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

Upvotes: 1068

Alonzzo2
Alonzzo2

Reputation: 1009

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!");    
}

Upvotes: 2

Shivam Bharadwaj
Shivam Bharadwaj

Reputation: 2296

String myUserName = Environment.UserName

This will give you output - your_user_name

Upvotes: 18

B Bhatnagar
B Bhatnagar

Reputation: 1816

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.

Upvotes: 17

priyesh jaiswal
priyesh jaiswal

Reputation: 161

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

Upvotes: 8

john rains
john rains

Reputation: 391

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;
        }
    }
}

Upvotes: 5

FlashTrev
FlashTrev

Reputation: 517

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.

Upvotes: 11

Amirali Eshghi
Amirali Eshghi

Reputation: 1011

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);
    }
}

Upvotes: 1

Kobus
Kobus

Reputation: 361

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.

Upvotes: 36

John Cuckaroo
John Cuckaroo

Reputation: 297

Use:

System.Security.Principal.WindowsIdentity.GetCurrent().Name

That will be the logon name.

Upvotes: 25

Michael Bakker
Michael Bakker

Reputation: 149

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;
    }
}

Upvotes: 5

Shivam657
Shivam657

Reputation: 743

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).

Upvotes: 27

Israel Margulies
Israel Margulies

Reputation: 8962

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.

Upvotes: 396

Daniel E.
Daniel E.

Reputation: 2059

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.

Upvotes: 13

Remy
Remy

Reputation: 252

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.

Upvotes: 11

JaredPar
JaredPar

Reputation: 755307

Try the property: Environment.UserName.

Upvotes: 130

jay_t55
jay_t55

Reputation: 11662

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.

Upvotes: 13

Related Questions