C#.NET Getting User Name of machine using Windows Service

微笑、不失礼 提交于 2020-01-11 09:38:08

问题


I am having difficulty getting the User Name of a person logged into a machine using a windows service.

When using both System.Environment.UserName or WindowsIdentity.GetCurrent().UserName I get NTAUTHORITY\SYSTEM but when this application gets pushed I need to be able to map to the UserID of the person logged in to the system. The operating system this will be used on will be Windows XP.

Any help would be very appreciated.


回答1:


For XP only, this advice should apply: Get Window Station for a non-interactive user per process, user or session?

  • Call OpenWindowStation to get a handle to "winsta0"
  • Call GetUserObjectInformation to find out who owns winsta0

However, this approach will break when you upgrade your app to Vista, Windows 7 or above, where services run in a different session from interactive logons. You'll need to call the terminal services API to get a list of logged on users, and pick your 'interactive' one.




回答2:


Try this:

var connectionOptions = new ConnectionOptions();
var scope = new System.Management.ManagementScope("\\\\localhost", connectionOptions);
var query = new System.Management.ObjectQuery("select * from Win32_ComputerSystem");
var searcher = new ManagementObjectSearcher(scope, query);
foreach (var row in searcher.Get()) 
{
    Console.WriteLine(row["UserName"].ToString().ToLower());
}



回答3:


Windows service always runs under the credential supplied in the service Properties / Log On tab. This has nothing to do with the credentials of the person / people that are currently logged into Windows in their own sessions.

The value of NTAUTHORITY\SYSTEM is correct because your service is running under 'Local System account' credentials.

You cannot run windows service under the account of 'currently logged on' user - that's not what windows service is for.



来源:https://stackoverflow.com/questions/4442488/c-net-getting-user-name-of-machine-using-windows-service

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