Get currently logged in user from a service running under LocalSystem account
Here goes the sample code:
using System.IO; using System.Management; using System.ServiceProcess; namespace MyTestService { public partial class MyTestService : ServiceBase { public MyTestService() { InitializeComponent(); } protected override void OnStart(string[] args) { TextWriter tw = new StreamWriter("c:\\success.txt"); tw.WriteLine("Successfully created file."); tw.WriteLine(CurrentUserName()); tw.Close(); } protected override void OnStop() { } private string CurrentUserName() { var s = new ManagementObjectSearcher ("SELECT UserName FROM Win32_ComputerSystem"); string str = string.Empty; foreach (ManagementObject moobj in s.Get()) { if (moobj["UserName"] != null) { str = moobj["UserName"].ToString(); } } return str; } } }
Related posts:























Leave a Reply
You must be logged in to post a comment.