Getting a User Or AllUsers from Active Directory using C#

public PrincipalContext GetPrincipalContext() 
       {
           PrincipalContext oPrincipalContext = new PrincipalContext(ContextType.Domain,"Your Domain Name"); 
           return oPrincipalContext; 
       }


To get the single user

public UserPrincipal GetUser(string userName) 
        { 
            PrincipalContext oPrincipalContext = GetPrincipalContext(); 
            UserPrincipal oUserPrincipal = 
               UserPrincipal.FindByIdentity(oPrincipalContext, userName); 
            return oUserPrincipal; 
        }

To get All Users

     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; 
           } 
       }

Comments

Popular posts from this blog

IRM and the Object Model

This content database has a schema version which is not supported in this farm

Activate and Deactivate Feature through PowerShell