Archive

Archive for January, 2013

Getting a User Or AllUsers from Active Directory using C#

January 2, 2013 1 comment

.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 🙂 .