title: Querying Active Directory using C# for user email by employee ID
body: <p>Is it possible to get a user's email from Active Directory using employeenumber as the query term? </p>
  
  <p>I am using C#'s <code>System.DirectoryServices</code> 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.</p>
  
  <p>Is there something wrong with my code? every time i run it, I get a Null Reference error on the <code>DirectoryEntry up_user =</code> line. I assume it is because the previous line is not getting any entities.</p>
  
  <p>Also, is there any good documentation on this topic? Everywhere I look, the posts are from 2011 or 2013.</p>
  
  <p>I have the following: </p>
  
  <pre><code>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 &amp;&amp; results.Count &gt; 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;
  }
  </code></pre>