1

I want to create a textblock that says "Welcome username".

username = current Windows user.

I'm working in a WPF project.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
user2579151
  • 55
  • 2
  • 7
  • 2
    Bug report: Why does it say `Welcome HP User` or `Welcome Valued Customer` in your app? – Cody Gray - on strike Jul 28 '13 at 13:38
  • 1
    The machine simply doesn't know the *correct* way to address the user. User account names are too frequently abbreviated and do not give you enough info to know whether a title is needed or the user finds it acceptable to be addressed by a machine with their first name. People are sticklers for details like that. You'd have to contact the domain controller to have a half-decent shot at it. System.DirectoryServices namespace. Given the risk of ticking off your user it is certainly best to just not do this. – Hans Passant Jul 28 '13 at 13:47

2 Answers2

6

You should use Environment.UserName (msdn):

Gets the user name of the person who is currently logged on to the Windows operating system.

Example:

Console.WriteLine("UserName: {0}", Environment.UserName);
kmatyaszek
  • 19,016
  • 9
  • 60
  • 65
5

If you want to get the user who is currently running the process, use:

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

OR

string userName = System.Environment.UserName

But the user you get from Environment.UserName is not guaranteed to be the user running the current process.

The difference between the two is explained in this comment:

The reason to prefer WindowsIdentity.GetCurrent() is that this returns the account that the application is running as. This is not necessarily the account that is currently logged into Windows (think "RunAs" or impersonation/delegation). So, if you want to know the logged-in user, use the Environment (if you trust it). If you want to know the security context your application is running as, using WindowsIdentity.GetCurrent().

Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185