how to get logged in user and machine name from window service in c#?

坚强是说给别人听的谎言 提交于 2020-01-02 10:05:31

问题


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.


回答1:


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.




回答2:


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());
}



回答3:


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

UPDATE

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



来源:https://stackoverflow.com/questions/4032619/how-to-get-logged-in-user-and-machine-name-from-window-service-in-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!