20

I need to programatically find the users name using C#. Specifically, I want to get the system/network user attached to the current process. I'm writing a web application that uses windows integrated security.

TylerH
  • 20,799
  • 66
  • 75
  • 101
minty
  • 22,235
  • 40
  • 89
  • 106
  • Your question is too vague. Are you trying to write an SQL query? Use some API? Get information from Active Directory? Please explain _exactly_ what you're trying to accomplish. – Juliet Dec 09 '08 at 00:27
  • 1
    Sorry I'm editing the question to be more specific. – minty Dec 09 '08 at 07:52

3 Answers3

39

The abstracted view of identity is often the IPrincipal/IIdentity:

IPrincipal principal = Thread.CurrentPrincipal;
IIdentity identity = principal == null ? null : principal.Identity;
string name = identity == null ? "" : identity.Name;

This allows the same code to work in many different models (winform, asp.net, wcf, etc) - but it relies on the identity being set in advance (since it is application-defined). For example, in a winform you might use the current user's windows identity:

Thread.CurrentPrincipal = new WindowsPrincipal(WindowsIdentity.GetCurrent());

However, the principal can also be completely bespoke - it doesn't necessarily relate to windows accounts etc. Another app might use a login screen to allow arbitrary users to log on:

string userName = "Fred"; // todo
string[] roles = { "User", "Admin" }; // todo
Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity(userName), roles);
Chris Schiffhauer
  • 17,102
  • 15
  • 79
  • 88
Marc Gravell
  • 1,026,079
  • 266
  • 2,566
  • 2,900
  • A small addition. In some cases you may want to set a [default principal](https://msdn.microsoft.com/en-us/library/system.appdomain.setthreadprincipal(v=vs.110).aspx) for threads of your application domain. It can be done like this `AppDomain.CurrentDomain.SetThreadPrincipal(myPrincipal);` – Korli Dec 23 '16 at 07:29
16

Depends on the context of the application. You can use Environment.UserName (console) or HttpContext.Current.User.Identity.Name (web). Note that when using Windows integrated authentication, you may need to remove the domain from the user name. Also, you can get the current user using the User property of the page in codebehind, rather than referencing it from the current HTTP context.

tvanfosson
  • 524,688
  • 99
  • 697
  • 795
4
string user = System.Security.Principal.WindowsIdentity.GetCurrent().Name ;
Mehdi Bugnard
  • 3,889
  • 4
  • 45
  • 86
  • 4
    While this code block may answer the question, it would be best if you could provide some explanation for why it does so. – DavidPostill Feb 10 '15 at 09:02