Get the current logged on user on Windows 7

By Perry

There is the difference in getting current logged on user on Windows Xp and Windows 7. This gives the method which works from current user context and doesn't need administrator privileges to get the current logged on user.

I had the big issue of getting current logged on user on Windows 7 and finally, I came out with below method which uses Win32_LogonSession. The WMI stuffs doesn't work efficient on Windows 7.

using System;
using System.Collections;
using System.Management;
using System.Text.RegularExpressions;
using System.Collections.Generic;

namespace CSharp.CodeSnippet.WMI
{

    public class Win32_LogonSession
    {

        public string AuthenticationPackage;
        public string LogonID;
        public LogonEventType LogonType;
        public string Name;
        public DateTime StartTime;

        public enum LogonEventType
        {
            System = 0,
            Interactive,
            Network,
            Batch,
            Service,
            Proxy,
            Unlock,
            NetworkClearText,
            NewCredentials,
            RemoteInteractive,
            CachedInteractive,
            CachedRemoteInteractive,
            CachedUnlock
        }

        static void Main(string[] args)
        {
            string query = "Select * From Win32_LogonSession";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            ManagementObjectCollection results = searcher.Get();

            List<Win32_LogonSession> list = new List<Win32_LogonSession>(results.Count);

            Dictionary<string, string> userTable = GetLoggedOnUsersTable();

            foreach (ManagementObject logonCurrent in results)
            {
                Win32_LogonSession entry = new Win32_LogonSession();
                if (userTable.ContainsKey(entry.LogonID))
                {
                    entry.Name = (string)userTable[entry.LogonID];
                    Console.WriteLine(entry.Name);
                }
            }
            Console.Read();
        }

        private static Dictionary<string, string> GetLoggedOnUsersTable()
        {
            string query = "Select * From Win32_LoggedOnUser";

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);

            ManagementObjectCollection results = searcher.Get();

            Dictionary<string, string> table = new Dictionary<string, string>(results.Count);

            foreach (ManagementObject currentObject in results)
            {
                string account = GetUser((string) currentObject["Antecedent"]);
                string session = GetLogonID((string) currentObject["Dependent"]);
                table.Add(session, account);
            }
            return table;
        }

        private static string GetLogonID(string propertyText)
        {
            string pattern = "LogonId=\"(?<id>\\d+)\"";
            Match matchID = Regex.Match(propertyText, pattern);
            if (matchID.Success)
            {
                return matchID.Groups["id"].Value;
            }
            else
            {
                return "";
            }
        }

        private static string GetUser(string propertyText)
        {
            string pattern = "Domain=\"(?<domain>[A-Za-z\\d_-]+)\"|Name=\"(?<name>[A-Za-z\\d\\s_-]+)\"";
            string domain = "";
            string name = "";
            foreach (Match matchCurrent in Regex.Matches(propertyText, pattern))
            {
                string fullText = matchCurrent.Groups[0].Value;
                if (fullText.StartsWith("Domain"))
                {
                    domain = matchCurrent.Groups["domain"].Value;
                }
                else
                {
                    name = matchCurrent.Groups["name"].Value;
                }
            }
            if (domain.Length == 0)
            {
                return name;
            }
            else
            {
                return domain + "\\" + name;
             }
         }
    }

}

Add System.Management reference and run the application. It will print current logged on users on windows 7.

Related FAQs

This is real project stuffs I am putting here. Will include more as and when I progress.
The windir root has been changed from Windows Xp to Window 7. We were using C:\WINNT in Windows 7 and it has changed to C:\Windows in Windows 7 that leads to make changes in configuration files for our applications.
There is a change in security mode from Windows Xp to Windows 7. UAC is one of the changes.
See http://www.eggheadcafe.com/sample-code/Windows7/e53b9d81-c025-4e41-a45c-f22214221c53/windows-7-uac-user-accou.aspx for UAC concept details. This shows how to disable it.
Get the current logged on user on Windows 7  (7314 Views)