Reputation: 157
How to get the logged in user (interactive user) and machine name from window service in c#. When i try Environment and other class to get logged in user name it just returns NT AUTHORITY\SYSTEM from window service.
Upvotes: 4
Views: 2373
Reputation: 1812
Simplest approach (at least, using Visual Studio 2017 Community Edition
and .Net Framework 4.7
) --
Namespace: System.Security.Principal
Code:
Console.WriteLine(WindowsIdentity.GetCurrent().Name);
The above will give you:
COMPUTERNAME\username
Yet another approach would be to use Environment
as in--
Console.WriteLine(Environment.UserName);
which will yield logged-in user's username
and
Console.WriteLine(Environment.MachineName);
which will yield the computer's or machine's name
Upvotes: 1
Reputation: 198
Try this code snippet
ManagementScope ms = new ManagementScope(@"\\.\root\cimv2");
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_ComputerSystem");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
foreach(ManagementObject mo in searcher.Get())
{
Console.WriteLine(mo["UserName"].ToString());
}
Upvotes: 1
Reputation: 17278
The service executes under the SYSTEM account, so that what you see in the Environment
class. The machine name should not be a problem (see Gmoliv's comment). Services execute independently from whoever may be logged on: that's one of the main reasons to have them.
If you want to find out what users (yes, there may be more than one) may be logged on to your computer, you'll have to use raw Windows API's AFAIK. If you really want this, one way could be to iterate through desktops, open the named desktop, get the associated user of each desktop, and look up the account name of the user (which returns the account name on the local machine). If you only want the user which may see something on screen, use OpenInputDesktop to get a handle instead of iterating through all of them.
Note that this requires your service to have higher access rights than usual. I'd be a bit suspicious of such a service myself.
Upvotes: 2