iamdeed
iamdeed

Reputation: 390

How do I solve error with Active Directory Search using user name

Im using the the below C# code to try search active directory for a user's email address by passing username. but this returns error

using System.Text;
using System;
using System.DirectoryServices;
public string GetADUserEmail(string userName)
{
    string domainpath = "LDAP://DC=domain,DC=local";
    DirectoryEntry searchRoot = new DirectoryEntry(domainpath);
    DirectorySearcher search = new DirectorySearcher(searchRoot);
    search.Filter = String.Format("(&(objectClass=user)(objectCategory=person))", userName);
    search.PropertiesToLoad.Add("mail");
    StringBuilder userEmail = new StringBuilder();

    SearchResult result = search.FindOne();
    if (result != null)
    {
        int emailCount = result.Properties["mail"].Count;

        for (int counter = 0; counter < emailCount; counter++)
        {
            userEmail.Append((string)result.Properties["mail"][counter]);
        }
    }
    return userEmail.ToString();
}

Upvotes: 0

Views: 459

Answers (1)

Cleptus
Cleptus

Reputation: 3541

That unkown error is likely because your pass arguments to string.Format without providing the correspondent placeholders in the string.

You must change the Filter to something similar to:

search.Filter = String.Format("(&(objectClass=user)(objectCategory=person)(SAMAccountName={0}))", userName);

Edit not related to your error: If a user has more than one email address, your usage of the StringBuilder is wrong (lack of separator character).

Upvotes: 2

Related Questions