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, ""))
    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);
the solution I have provided is from

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