简体   繁体   中英

How can I search for both the user's last name AND the first name in the Active Directory using C#

I have this code that works very well when I want to search JUST for the user's last name

    public static string GetPhoneFromAD()
    {
        try
        {
            DirectoryEntry entryDomain = new DirectoryEntry("LDAP://" + domain);
            DirectorySearcher ds = new DirectorySearcher(entryDomain);

            string currentContextIdentity = System.Web.HttpContext.Current.User.Identity.Name;

            string lastName = currentContextIdentity.Split(' ')[currentContextIdentity.Split(' ').Length - 1];

            ds.Filter = "(sn=" + lastName + ")";
            SearchResult sr = ds.FindOne();

            string telephoneNumber = sr.Properties["telephoneNumber"][0].ToString();
            return FormatPhone(telephoneNumber);
        }
        catch (Exception exception)
        {
            drmsda.InsertErrorlog("manage.aspx.cs", "Error in an attempt to get the phone number", exception.Source, exception.Message + " " + exception.StackTrace, "");
            drmsda.sendErrorEmail("Error: SetPhone generated email", exception.Message);
            return string.Empty;
        }
    }

However, if the user's last name is common, like Smith, I won't the right entry. Thus, I would like to add another criteria, such as first name. However, the query I came up with is not working. I did try the following

ds.Filter = "(givenName=" + firstName  + "&sn=" + lastName + ")";

But that is not working, can somebody help?

Thank you in advance

LDAP filter syntax is a bit different to that; you want:

 (&(givenName=joe)(sn=bloggs))

See here for many examples.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM