Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles
(untagged)

Enumerating Users using WMI.NET and C#

0.00/5 (No votes)
9 Jan 2008 1  
Enumerate all the available users, groups using WMI.NET and C#

Introduction

Recently, I had to get all the user names in my local machine. I was searching for a proper method and it was really hard to get one. I knew I have to use WMI, but the biggest obstacle was of combining different WMI queries to get the result.

Background

The WMI classes that immediately came into my mind were as listed below:

Each of the classes has its own use. However, Win32_Account forms the main class and other classes derive Win32_Account.

Using the Code

To get all user accounts, you could just query:

select * from Win32_UserAccount where Domain=’YOURDOMAIN’

And to get all groups, you could just query:

select * from Win32_GroupUser where Domain=’YOURDOMAIN’

Using C# for user accounts:

public static void GetUsers()
{
     SelectQuery sQuery = new SelectQuery(“Win32_UserAccount”,“Domain=’CHAKS-PC’”);

     try
     {
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

            Console.WriteLine(“User Accounts”);
            Console.WriteLine(“”);

            foreach (ManagementObject mObject in mSearcher.Get())
            {
                Console.WriteLine(mObject[“Name”]);
            }
      }
      catch (Exception ex)
      {
            Console.WriteLine(ex.ToString());
      }

     Console.ReadKey();
 }

Using C# for groups:

public static void GetGroups()
 {
       SelectQuery sQuery = new SelectQuery(“Win32_Group”, “Domain=’CHAKS-PC’”);

       try
       {
             ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);

             Console.WriteLine(“Groups”);
             Console.WriteLine(“”);

             foreach (ManagementObject mObject in mSearcher.Get())
             {
                 Console.WriteLine(mObject[“Name”]);
             }
        }
        catch (Exception ex)
        {
             Console.WriteLine(ex.ToString());
        }

        Console.ReadKey();
 }

Now to get users corresponding to a particular group, we need to query Win32_GroupUser and there comes the trick.

The Win32_GroupUser is an association class and relates a group and the account to which that is a member of that group.

So, now our query changes to:

select * from Win32_GroupUser where _
    GroupComponent=’”‘Win32_Group.Domain=’domain-name’,Name=’group-name””‘

And our C# code changes to:

public static void GetUsers(String DomainName, String GroupName)
{
      #region Build WMI query using SelectQuery
      ///<summary>
      /// Alternate method for building query
      /// Which I think is better approach
      ///</summary>
      StringBuilder sBuilder = new StringBuilder(“GroupComponent=”);
      sBuilder.Append(‘”‘);
      sBuilder.Append(“Win32_Group.Domain=”);
      sBuilder.Append(“‘”);
      sBuilder.Append(DomainName);
      sBuilder.Append(“‘”);
      sBuilder.Append(“,Name=”);
      sBuilder.Append(“‘”);
      sBuilder.Append(GroupName);
      sBuilder.Append(“‘”);
      sBuilder.Append(‘”‘);
      SelectQuery sQuery = new SelectQuery(“Win32_GroupUser”, sBuilder.ToString());
      #endregion           

      ///<summary>
      /// Execute the query
      /// Construct a ManagementPath from the PartComponent and check for ClassName
      /// and extract the UserName
      /// Depending on which method you used to build the query,
      /// pass the String or SelectQuery object to ManagementObjectSearcher
      ///</summary>
      try
      {
            ManagementObjectSearcher mSearcher = new ManagementObjectSearcher(sQuery);
            foreach (ManagementObject mObject in mSearcher.Get())
            {
                 ManagementPath path = 
                        new ManagementPath(mObject[“PartComponent”].ToString());
                 if (path.ClassName == “Win32_UserAccount”)
                 {
                      String[] names = path.RelativePath.Split(‘,’);
                      Console.WriteLine(names[1].Substring(names[1].IndexOf(“=”) 
                            + 1).Replace(‘”‘, ‘ ‘).Trim());
                 }
            }
      }
      catch (Exception ex)
      {
            Console.WriteLine(ex.ToString());
      }

      Console.ReadKey();
}

Hope you enjoyed reading my article.

If you have any queries, please do email me or start a discussion below.

History

  • 10th January, 2008 - Initial post

License

This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below.

A list of licenses authors might use can be found here