Home > C# > Getting a User Or AllUsers from Active Directory using C#

Getting a User Or AllUsers from Active Directory using C#

.NET 3.5 introduced System.DirectoryServices.AccountManagement which manages directory objects independent of System.DirectoryServices namespace. I will be focusing on getting user and AllUsers from AD using AccountManagement dll.

To make is short just attaching code snippet. Details can be acquired from the link which helped me a lot.

After adding the reference in project and namespace in class. We need to have the following functions.

This one gets the domain with the system is connected.

        ///// <summary>
       ///// Gets the base principal context
      ///// </summary>
     ///// <returns>Returns the PrincipalContext object which contains Domain</returns>
       public PrincipalContext GetPrincipalContext()
       {

           PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain);
           return oPrincipalContext;
       }

To get a specific user.

        /// <summary>
        /// Gets a certain user on Active Directory
        /// </summary>
        /// <param name="sUserName">The username to get</param>
        /// <returns>Returns the UserPrincipal Object</returns>
        public UserPrincipal GetUser(string sUserName)
        {
            PrincipalContext oPrincipalContext = GetPrincipalContext();
            UserPrincipal oUserPrincipal =
               UserPrincipal.FindByIdentity(oPrincipalContext, sUserName);
            return oUserPrincipal;
        }

To get all users.

        /// <summary>
       /// Getting all users of AD and adding them into List.
       /// </summary>
       /// <returns></returns>
       public List<string> GetAllUsers()
       {
           try
           {
               List<string> users = new List<string>();

               PrincipalContext oPrincipal = GetPrincipalContext();
               GroupPrincipal gPrincipal = GroupPrincipal.FindByIdentity(oPrincipal, IdentityType.SamAccountName, "Domain Users");

               if (gPrincipal != null)
               {
                   foreach (Principal p in gPrincipal.GetMembers(false))
                   {
                       users.Add(p.DisplayName);
                   }
               }

               return users;
           }
           catch (Exception ex)
           {

               throw ex;
           }
       }

Hope this helps 🙂 .

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: