35

There's really no pressing reason for me to ask this question other than curiosity - using C#, is there a way to determine from within code which user my process is running as? To illustrate using code:

static void Main(string[] args) { string userID; //what goes here to fill in this userID variable? Console.out.WriteLine(string.Format("This process is running as {0}.", userID)); } 

3 Answers 3

64
string userID = WindowsIdentity.GetCurrent().Name 

From MSDN: WindowsIdentity.GetCurrent() and WindowsIdentity.Name

Sign up to request clarification or add additional context in comments.

3 Comments

And this doesn't just get who I'm logged in as, it would return LOCAL SYSTEM or NETWORK SERVICE or the like if the process was running under one of those accounts?
Environment.UserName is the more conventional shortcut for this, I think.
@Zann, that is correct, it returns the process' identity, not the user account that is logged in, although they may be the same or they may not be. It will correctly return LOCAL SYSTEM or NETWORK SERVICE, for example, in a typical IIS worker process. @Hans: OP asked for the process' identity, not the current user logged into to the console/session (although they can be the same!)
4

string UserID = Environment.UserName;

Comments

2

There are a variety of ways, depending on what type of application you're running.

Here's an article on using the Thread Principal to check user data / authorization.

This thread contains a couple of other approaches, though not much elaboration.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.