0

I'm using C# with .NET 3.5

My goal here is to take the logged in user name and simply start a process under this user name. Normally a simple Process.Start(pathToProgram) would help here, but the problem is that I'm calling this line from an installer class, meaning the msiexec is currently working and the user name i get is SYSTEM instead of the actual user who currently logged in to windows.

Of course that Environment.UserName also returns "SYSTEM" instead of the logged in user.

How can I start the process as the logged in user and not as the user SYSTEM?

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • Not able to test now, but did you try to call `Environment.GetEnvironmentVariable("USERNAME");` ? It is different from Environment.UserName in your particular context? – Steve Jul 28 '13 at 13:01
  • There is no such thing as "the logged in user". Remember that Windows is a multi-user operating system. It's possible to have no users logged in, one user, multiple users, multiple *remote* users, and any combination of the above. So you'll need to define more clearly what you mean by "the logged in user" and how you want to handle these other cases. – Cody Gray - on strike Jul 28 '13 at 13:06
  • the logged in user is the user name which entered his name and password in the windows login screen – CodeMonkey Jul 28 '13 at 13:43
  • @Steve your suggestion was the winning suggestion and it did work. Why did it give me the user name I was searching for and the other suggestions didn't? If you write it as an answer, I will accept it as the correct answer. – CodeMonkey Jul 28 '13 at 13:55

2 Answers2

0

You can get the userName for current logged in user like this -

string userName = System.Security.Principal.WindowsIdentity.GetCurrent().Name;

From SO post -

Process p = new Process();
p.StartInfo.FileName = "C:\SetupVM.bat";
p.StartInfo.UserName = userName;
p.StartInfo.Password = "AdminPassword";
p.Start();
p.WaitForExit();
Community
  • 1
  • 1
Rohit Vats
  • 79,502
  • 12
  • 161
  • 185
0

I think that when you call Environment.UserName you get the value for the user impersonated by the current process, while if you call Environment.GetEnvironmentVariable("USERNAME") you get the name of the user that starts the process and at that point the process is not started and, of coure, has not yet impersonated another user.

However, this is only a raw thought that seems to work for the OP question, but I still searching some reference material to confirm my assertion.
I welcome any one that has a better understanding of this fact and explain it better than me

Steve
  • 213,761
  • 22
  • 232
  • 286
  • Maybe you want to try getting another correct answer for a follow up question I've got: http://stackoverflow.com/questions/17908993/starting-a-process-with-a-user-name-and-password – CodeMonkey Jul 28 '13 at 14:12