0

I am writing an application that will run on windows server. The scenario is that user will login using normal domain account and application will run using administrator account. I need to get the user currently logged in to windows to do some processing.

when I get user name using following method it gives me the admin account used to run the exe and not the account logged in to windows current session.

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

Then I tried following method to get the logged in user

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem");
ManagementObjectCollection collection = searcher.Get();

string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"];

This code is working fine on windows 10 and giving me the user currently logged in to windows. But on windows server 2012 it is returning empty string.

How can I get the logged in user when running the exe on windows server?? I dont want to know how many sessions are running on windows server. i want to know the current logged in user.

ghengalala
  • 109
  • 9
  • Absent any smarter solution, perhaps an exe you start normally can get the username, and then start your main app as an administrator, passing the normal username as a command line arg.. alternatively, your wmi approach but get the name of a process that runs under that user when the user logs on, such as explorer.. tight now you're just picking the first process blindly. Though remember that in a server context especially there may be multiple logged in users at the same time - https://stackoverflow.com/questions/777548/how-do-i-determine-the-owner-of-a-process-in-c – Caius Jard Mar 05 '21 at 06:39
  • Also review the answers in https://stackoverflow.com/questions/1240373/how-do-i-get-the-current-username-in-net-using-c - if none of them work, you show you've tried them – Caius Jard Mar 05 '21 at 07:08

1 Answers1

-1

In Windows, current logged-on user is written to environment variable USERNAME, his domain - to USERDOMAIN, and you can read this values with System.Environment.GetEnvironmentVariable()

You can list all (currently set) environment variables with set command in console/command prompt.

Dmitry
  • 16,110
  • 4
  • 61
  • 73
  • 2
    I suspect that this will also return the admin account used to run the exe, not the name of the logged on user – Caius Jard Mar 05 '21 at 07:05