Question

Is it possible, using System.DirectoryServices.AccountManagement, to find who the user is who is currently logged into a specific pc?

Using the PrincipalSearcher it is easy to find all the computers on a domain, and even when they were last logged into. However, I can’t find an easy way to find the usernames of users logged into what pcs.

Any ideas on how to do this?

Was it helpful?

Solution

To find currently logged in users you need to know which processes are running from the user accounts. So for each PCs you need to get list of processes and find under which account the process executed. To do this you can use WMI.

   const string ns = @"root\cimv2";

   var host = "your host";

   var scope = new ManagementScope(string.Format(@"\\{0}\{1}", host, ns));

   scope.Connect();

//List of logged in users

   using (var searcher = new ManagementObjectSearcher(scope, 
           new ObjectQuery("select * from Win32_LoggedOnUser")))
   {

          foreach (var logonUser in searcher.Get())
          {
               //see MSDN for available properties of Win32_LoggedOnUser, 
               //take into consideration "Dependent", "Antecedent" properties
          }

   }

//list of processes

  using (var searcher = new ManagementObjectSearcher(scope, 
                  new ObjectQuery( "select * from Win32_SessionProcess")))
  {
       foreach (var sessProc in searcher.Get())
       {
            //see "Antecedent" property
       }
  }
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top