Siddharth
Siddharth

Reputation: 141

I am writing c# code wherein I want search for the details of a specific user from Active Directory

enter image description hereI got a very useful code:

using (var context = new PrincipalContext(ContextType.Domain, "redmond.corp.microsoft.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(); 

But the issue is that it lists down all the user of a domain, and I want to search the details based on the user specified logon name.

I tried a lot to modify the code as per my need, but I always get a reference exception.

Upvotes: 0

Views: 191

Answers (1)

MethodMan
MethodMan

Reputation: 18863

using (PrincipalContext context = new PrincipalContext(ContextType.Domain)) //pass in your domain as the second param if needed as well 
{
    using (UserPrincipal user = UserPrincipal.FindByIdentity(context,"yourusernamehere"))
    {
        if (user != null)
        {
            fullName = user.DisplayName;
        }
    }
}

look at all the property's of the userobject when inspecting in the Debugger / QuickWatch and you can see email address etc...

Upvotes: 1

Related Questions