Question : C# WMI query for getting current logged on user doesn't work on Windows 7

Hi,

The following code doesn't work on Windows 7 but works on Windows xp. Could anyone please tell me what are the changes I need to make for Windows 7?

Thanks.
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Management;

namespace ConsoleApplication1
{
    class Program
    {
        static void Main(string[] args)
        {
            try
            {
                ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT username FROM Win32_ComputerSystem");

                foreach (ManagementObject queryObj in searcher.Get())
                {
                    Console.WriteLine("UserName: {0}", queryObj["username"].ToString());
                }
            }
            catch
            {
                Console.WriteLine("Exception");
            }
            Console.Read();
        }
    }
}

Answer : C# WMI query for getting current logged on user doesn't work on Windows 7

You can try a Win32_LogonSession query instead:

1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:
64:
65:
66:
67:
68:
69:
70:
71:
72:
73:
74:
75:
76:
77:
78:
79:
80:
81:
82:
83:
84:
85:
86:
87:
88:
89:
90:
91:
92:
93:
94:
95:
96:
97:
98:
99:
100:
101:
102:
103:
104:
105:
106:
107:
108:
109:
110:
111:
112:
113:
114:
115:
116:
117:
118:
119:
120:
121:
122:
123:
124:
125:
126:
127:
128:
129:
130:
131:
132:
133:
134:
135:
136:
137:
138:
139:
// Add a reference to System.Management.dll to the project.

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
        }

        public static List<Win32_LogonSession> GetList()
        {
            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();

                entry.AuthenticationPackage = (string) logonCurrent["AuthenticationPackage"];
                entry.LogonID = (string) logonCurrent["LogonID"];
                entry.LogonType = (LogonEventType) Convert.ToInt32(logonCurrent["LogonType"]);
                entry.StartTime = ConvertFileTime((string) logonCurrent["StartTime"]);
                if (userTable.ContainsKey(entry.LogonID))
                {
                    entry.Name = (string) userTable[entry.LogonID];
                }
                list.Add(entry);
            }
            return list;
        }

        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;
            }
        }

        private static DateTime ConvertFileTime(string time)
        {
            if (time != null)
            {
                const string FILE_TIME_MASK = "yyyyMMddHHmmss";
                time = time.Substring(0, time.IndexOf("."));
                return DateTime.ParseExact(time, FILE_TIME_MASK, null);
            }
            return DateTime.MinValue;
        }
    }

}
Random Solutions  
 
programming4us programming4us