Friday 11 March 2016

Get all users from active directory using c#


I needed to get all members  from active directory using c#.
Now the solution I have found is as follows


using (var context = new PrincipalContext(ContextType.Domain, "yourdomain.com"))
{
    using (var searcher = new PrincipalSearcher(new UserPrincipal(context)))
    {
        foreach (var result in searcher.FindAll())
        {
            DirectoryEntry de = result.GetUnderlyingObject() as DirectoryEntry;
            Console.WriteLine("First Name: " + de.Properties["givenName"].Value);
            Console.WriteLine("Last Name : " + de.Properties["sn"].Value);
            Console.WriteLine("SAM account name   : " + de.Properties["samAccountName"].Value);
            Console.WriteLine("User principal name: " + de.Properties["userPrincipalName"].Value);
            Console.WriteLine();
        }
    }
}
Console.ReadLine();
the solution I have provided is from http://stackoverflow.com/questions/5162897/how-can-i-get-a-list-of-users-from-active-directory


Now the directory entry contains properties defined as string or object and you need to make sure that the data are accessed correctly.



No comments:

Post a Comment