'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();
}


Solution 1:[1]

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).

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1