Link to home
Start Free TrialLog in
Avatar of pkoivula
pkoivulaFlag for United States of America

asked on

Get windows username in c# windows service in 64-bit Windows 7

Hi,

How to get the current logged in username from C# Windows service in Windows 7 64-bit system.

I'm using the following code which works fine in 32-bit Windows:


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

Thanks
Avatar of APoPhySpt
APoPhySpt
Flag of Portugal image

hi, have you tried:



using System.Security.Principal;
......
WindowsPrincipal wp = new WindowsPrincipal(WindowsIdentity.GetCurrent());
String username = wp.Identity.Name;

Or

For UserName ->  System.Security.Principal.WindowsIdentity.GetCurrent().User

For ComputerName ->  System.Security.Principal.WindowsIdentity.GetCurrent().Name
Avatar of pkoivula

ASKER

Hello APoPhySpt,

Thanks for the reply but the solution you provide wont work for the Windows Service. My requirement is to get the current logged in username in which my windows service is runnng. The above code works for  windows application but not windows service.

Thanks
ASKER CERTIFIED SOLUTION
Avatar of Jacques Bourgeois (James Burger)
Jacques Bourgeois (James Burger)
Flag of Canada image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
OK, thanks, I'll try that.
This code is run on 64 bit windows service but not get exact user name "NT AUTHORITY\SYSTEM". Please suggest any thing else.