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

时间:2018-03-06 13:02:43

标签: c# windows-services

I have code For LoggedIn User For windows service. I had used the below code to get the loggedin user

 public string LoggedInUserName()
        {
            string LoggedInUser = null;
            ManagementScope ms = new ManagementScope("\\\\.\\root\\cimv2");
            System.Management.ObjectQuery query = new System.Management.ObjectQuery("SELECT * FROM Win32_ComputerSystem");
            ManagementObjectSearcher searcher = new ManagementObjectSearcher(ms, query);
            foreach (ManagementObject mo in searcher.Get())
            {
                LoggedInUser = mo["UserName"].ToString();
            }
            return LoggedInUser;
        }

protected override void OnSessionChange(SessionChangeDescription changeDescription)
        {
            string UserName=null;
            FileStream fs = new FileStream(@"d:\TimeInfo.txt",
            FileMode.OpenOrCreate, FileAccess.Write);
            StreamWriter sWriter = new StreamWriter(fs);
            sWriter.BaseStream.Seek(0, SeekOrigin.End);
            string UserName = LoggedInUserName();

            switch (changeDescription.Reason)
            {
                case SessionChangeReason.SessionLogon:
                    sWriter.WriteLine(UserName + " System Log On Time: \t " + DateTime.Now);
                    break;
                case SessionChangeReason.SessionLogoff:
                    sWriter.WriteLine(UserName + " System Log Off Time: \t " + DateTime.Now);
                    break;

                default:
                    break;
            }
            sWriter.Flush();
            sWriter.Close();
        }

The UserName is showing for only at the time of LogIn, but it is not showing the username at the time of log-off How can i get LoggedOut user name in windows service

please help me...

0 个答案:

没有答案