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.

+11  A: 

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.


For something this simple, you should probably run a google search before posting to a site like this.

As a VB.Net programmer, I think that I've used "System.Environment.UserName" in the past. I think that that should work in C# as well.

I disagree. This site should have answers to all kinds of programming questions. I looked for the answer within stackoverflow and since it wasn't here I thought I would ask it so that future seekers will find it.
Unless people ask and answer questions like this on sites like this, google won't have anything to find in the first place!!
+5  A: 

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,, 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);
Marc Gravell