Share via


How can I get the logged in User ID in C#

Question

Thursday, August 27, 2009 9:41 PM

Is there a way to get the User ID for Windows XP/Vista at runttime with C#?

All replies (4)

Thursday, August 27, 2009 9:43 PM ✅Answered

Note that this won't work when you're trying to run from a service, as a service runs with another user account and in another desktop, but otherwise, the following code will work to get this value as a string.

System.Security.Principal.WindowsIdentity.GetCurrent().NameCoding Light - Illuminated Ideas and Algorithms in Software
Coding Light WikiTwitterLinkedInForumsBrowser


Thursday, August 27, 2009 10:02 PM

Thank you, David. I also found this:

System.Environment.UserName

Is the one you provided preferable?


Thursday, August 27, 2009 10:04 PM

Hi,

Note the value return by 

System.Security.Principal.

WindowsIdentity.GetCurrent()

is disposable so technically, to be clean, you should do;

  string userName = null;
  using (System.Security.Principal.WindowsIdentity wi = System.Security.Principal.WindowsIdentity.GetCurrent())
  {
    userName = wi.Name;
  }

Or you can use this alternate function if you are in a Windows Forms app;

System.Windows.Forms.SystemInformation.UserName

which just returns a string and needs no dispose in your own code.

As David said, neither one will return the value of the logged on user if you are running in a service as the service runs as a specified user account.


Thursday, August 27, 2009 10:05 PM | 1 vote

In which case, System.Environment.UserName would probably be best.  Use that. /* makes a mental note */Coding Light - Illuminated Ideas and Algorithms in Software
Coding Light WikiTwitterLinkedInForumsBrowser