title: Get the logged on user name in C#
body: <p>How do i get the current logged on user name in windows 7 (i.e the user who is physically logged on to the console in which the program that i am launching is running).</p>
  
  <p>For example if i am logged on as "MainUser" and run my console application (that will display the logged on user name) as "SubUser", then the program only returns "SubUser" as the currently logged on user.</p>
  
  <p>I used the following 2 techniques to get the user name. Both are not getting me the thing that i want.</p>
  
  <pre><code>System.Environment.GetEnvironmentVariable("USERNAME")
  System.Security.Principal.WindowsIdentity.GetCurrent().User;
  </code></pre>
  
  <p>Note that however, this VBScript code returns the logged on user name irrespective of the user account from which this script is run:</p>
  
  <pre><code>strComputer = "." 
  Set objWMIService = GetObject("winmgmts:" _ 
      &amp; "{impersonationLevel=impersonate}!\\" &amp; strComputer &amp; "\root\cimv2") 
  Set compsys_arr = objWMIService.ExecQuery _ 
      ("Select * from Win32_ComputerSystem") 
  For Each sys in compsys_arr
      Wscript.Echo "username: " &amp; sys.UserName
  Next
  </code></pre>
  
  <p>Any way it is possible in C#?</p>