Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I get the currently-logged username from a Windows service in .NET?

I have a Windows service which need the currently logged username. I tried System.Environment.UserName, Windows identity and Windows form authentication, but all are returning "System" as the user as my service is running in system privileged. Is there a way to get the currently logged in username without changing my service account type?

like image 700
Raj Avatar asked Mar 07 '11 10:03

Raj


People also ask

How to get username from Windows service c#?

WindowsIdentity. GetCurrent(). Name; But, it is giving the output "NT AUTHORITY\SYSTEM " as the current user name after deploying the service.

How can I see logged in username in asp net?

User property in ASP.Net MVC Razor. In this article I will explain with an example, how to display Welcome Username after Login in ASP.Net MVC Razor. The Login Form will be implemented using Forms Authentication and Entity Framework and the Username will be displayed using the HttpContext.


1 Answers

This is a WMI query to get the user name:

ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT UserName FROM Win32_ComputerSystem"); ManagementObjectCollection collection = searcher.Get(); string username = (string)collection.Cast<ManagementBaseObject>().First()["UserName"]; 

You will need to add System.Management under References manually.

like image 125
Tapas Avatar answered Oct 17 '22 23:10

Tapas