Directory Services

Enumerating User Memberships

This topic includes information and a code example that shows how to use a Windows form to enumerate the groups that a user is the member of.

Creating a Windows Form to Display a User's Memberships

  1. Open Visual Studio .NET and select New Project.
  2. From Project Types, select Visual C# or Visual Basic and from Templates, select Windows Application.
  3. Name your project and select OK.
  4. Select Project>Add Reference... and select System.DirectoryServices from the list displayed on the .NET tab.
  5. On the form design page, drag a text box from the Toolbox to the form and format it. This is where the user will add a user name to bind to.
  6. Drag a label from the Toolbox to the form and modify the Text property to read "Enter Name:"
  7. Drag a button from the Toolbox to the form and modify the Text property to read "Find Groups".
  8. Drag a ListBox from the Toolbox to the form. This is where the results will be displayed.
  9. Double-click the form to go to the code page.
  10. Add the "using System.DirectoryServices;" statement to the end of the using statement list.
  11. Add the following code example to main.
    [C#]
    static void Main() 
    {
    	Application.Run(new Form1());
    }
    private void label1_Click(object sender, System.EventArgs e)
    {
    }
    private void textBox1_TextChanged(object sender, System.EventArgs e)
    {
    }
    private void button1_Click(object sender, System.EventArgs e)
    {
    	string strUserADsPath = "LDAP://fabrikam/cn=" +textBox1.Text +",cn=users,dc=fabrikam,dc=com";
    	DirectoryEntry oUser;
    	oUser = new DirectoryEntry(strUserADsPath);
    	listBox1.Items.Add("Groups to which {0} belongs:"+ oUser.Name);
    	// Invoke IADsUser::Groups method.
    	object groups = oUser.Invoke("Groups");
    	foreach ( object group in (IEnumerable)groups)   
    	{
    		// Get the Directory Entry.
    		DirectoryEntry groupEntry  = new DirectoryEntry(group);
    		listBox1.Items.Add(groupEntry.Name); 
    }
    }
    	private void Form1_Load(object sender, System.EventArgs e)
    	{ 	 
    }   
    }
    
  12. Compile and run the application.