Click here to Skip to main content
15,879,490 members
Articles / Desktop Programming / Win32
Article

Enumerating Users using WMI.NET and C#

Rate me:
Please Sign up or sign in to vote.
2.67/5 (5 votes)
9 Jan 2008CPOL1 min read 82.7K   944   26   7
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:

SQL
select * from Win32_UserAccount where Domain=’YOURDOMAIN’

And to get all groups, you could just query:

SQL
select * from Win32_GroupUser where Domain=’YOURDOMAIN’

Using C# for user accounts:

C#
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:

C#
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:

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

And our C# code changes to:

C#
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, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer
New Zealand New Zealand
Chakkaradeep, known as Chaks to his friends, hails from the Indian subcontinent.Having done his Masters in Software Engineering, he knows his way around a computer and has sound knowledge of Microsoft technologies.

Chaks is currently working as a Microsoft Developer @ New Zealand.

You can reach him via his blog - http://chakkaradeep.wordpress.com

Comments and Discussions

 
Questionselecting the user list using the CIMV2 scope Pin
Tarek Elqusi22-Dec-12 9:34
professionalTarek Elqusi22-Dec-12 9:34 
GeneralGroups for a user: code works but is very slow! Pin
kenshiro200014-Apr-08 5:07
kenshiro200014-Apr-08 5:07 
GeneralRe: Groups for a user: code works but is very slow! Pin
Murali Krishna Babu22-Nov-10 18:28
Murali Krishna Babu22-Nov-10 18:28 
Generalno update if we change the the users accounts name, please help Pin
Member 407499322-Mar-08 15:11
Member 407499322-Mar-08 15:11 
GeneralRe: no update if we change the the users accounts name, please help Pin
chakkaradeepcc27-Mar-08 0:51
chakkaradeepcc27-Mar-08 0:51 
GeneralInvalid Zip file Pin
KChandos9-Jan-08 7:32
professionalKChandos9-Jan-08 7:32 
The source attached to the article downloads as an invalid zip file.
AnswerRe: Invalid Zip file Pin
chakkaradeepcc9-Jan-08 7:51
chakkaradeepcc9-Jan-08 7:51 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.