Is it possible to get a user's email from Active Directory using employeenumber as the query term?
I am using C#'s System.DirectoryServices and am a little bit lost. The previous developer at my company was using this process, but he had an email and was querying for the employee number. I have changed it to what I believe it should be, but to be honest, I don't understand the code that well.
Is there something wrong with my code? every time i run it, I get a Null Reference error on the DirectoryEntry up_user = line. I assume it is because the previous line is not getting any entities.
Also, is there any good documentation on this topic? Everywhere I look, the posts are from 2011 or 2013.
I have the following:
try
{
    string email = string.Empty;
    ContextType authenticationType = ContextType.Domain;
    PrincipalContext principalContext = new PrincipalContext(authenticationType, "MATRIC");
    UserPrincipal userPrincipal = null;
    userPrincipal = UserPrincipal.FindByIdentity(principalContext, empnum);
    DirectoryEntry up_User = (DirectoryEntry)userPrincipal.GetUnderlyingObject();
    DirectorySearcher deSearch = new DirectorySearcher(up_User);
    SearchResultCollection results = deSearch.FindAll();
    if (results != null && results.Count > 0)
    {
        ResultPropertyCollection rpc = results[0].Properties;
        foreach (string rp in rpc.PropertyNames)
        {
            if (rp == "mail") 
            {
                email = rpc["mail"][0].ToString();
            }
        }
        if (email != string.Empty)
        {
            return email;
        }
        return null;
    }
            return null;
}
catch (Exception ex)
{
    throw ex;
}