How to get the groups of a user in active directory c asp net


Active Directory is a directory developed by Microsoft that allows network administrators to manage and organize resources in a network. In ASP.NET, you may need to retrieve the groups of a user in Active Directory for various purposes, such as access or displaying user information. In this article, we will explore how to this using C# in ASP.NET.


Before we dive into the code, make sure you have the following prerequisites:

  • Studio on your machine
  • An Active Directory server with user groups set up

Step 1: Connecting to Active Directory

To retrieve the groups of a user in Active Directory, we first need to establish a connection to the Active Directory server. We can use the DirectoryEntry class in C# to achieve this. Here's an example:

using .DirectoryServices;

string activeDirectoryPath = "LDAP://";
string username = "yourusername";
string password = "yourpassword";

DirectoryEntry directoryEntry = new DirectoryEntry(activeDirectoryPath, username, password);

In the above code, replace with the domain name of your Active Directory server, and provide the appropriate username and password to authenticate.

Step 2: Retrieving User Information

Once we have established a connection to the Active Directory server, we can retrieve the user information, including the groups they belong to. We can use the DirectorySearcher class to a search query. Here's an example:

In the above code, we create a DirectorySearcher object and set the filter to search for a user with the specified username. We then retrieve the first search and get the memberOf property, which contains the groups the user belongs to. Finally, we iterate over the groups and them to the console.

Step 3: Displaying the Groups

Now that we have retrieved the groups of the user, we can display them in our ASP.NET application. Let's assume we have a label control with the ID lblGroups in our ASP.NET page. Here's an example of how to display the groups:

lblGroups.Text = string.Join(", ", groups);

In the above code, we use the string.Join to concatenate the groups into a comma-separated string and assign it to the Text property of the label control.


In this article, we have explored how to retrieve the groups of a user in Active Directory using C# in ASP.NET. By establishing a connection to the Active Directory server, performing a search query, and retrieving the user's group information, we can effectively manage access control and display user information in our ASP.NET applications.

Rate this post

Leave a Reply

Your email address will not be published. Required fields are marked *

Table of Contents