Search code examples
c#user-profile

Get all users that have ever logged into a pc with c#


I'm trying to retrieve all the users that have ever logged into a pc and populate them in a combobox, but after searching, I'm not finding any good answers.

I was going to look at the:

DirectoryInfo(Environment.GetEnvironmentVariable("USERPROFILE")).Parent.GetDirectories();

But I feel that is way to unreliable.

Next I was going to look at the registry, but after reading, that list will not update if a user account name has ever been changed. I know there has to be a record of all the user profiles on a machine, because I have used Microsoft systernals tools to manage them. but I just cannot figure out how to do it programatically with c#.


Solution

  • Ok, well, i figured this out, actually with WMI after all, here is my code.

    using System.Security.Principal;
    using System.Management;
    private void GetLocalUserAccounts()
    {
         SelectQuery query = new SelectQuery("Win32_UserProfile");
         ManagementObjectsSearcher searcher = new ManagementObjectSearcher(query);
         foreach (ManagementObject sid in searcher.Get())
         {
              MessageBox.Show(new SecurityIdentifier(sid["SID"].ToString()).Translate(typeof(NTAccount)).ToString());
         }
    }
    

    This also returns the system accounts IE: NT_Authority NT_System, but those can be filtered easily. Thanks for all the help.