title: Method to get user details from LDAP/AD
body: <p>I'm using the code below to get various information about the logged in user and it works, but I want to turn it into a method where I can pass the attribute I want (<code>DisplayName</code>, <code>EmailAddress</code>, etc) and it returns that value for whoever is logged in. I couldn't figure out how to get this to work though.</p>
  
  <pre><code>using (PrincipalContext context = new PrincipalContext(ContextType.Domain))
  {
      using (UserPrincipal user = UserPrincipal.FindByIdentity(context, User.Identity.Name))
      {
          if (user != null)
          {
              loggedInUserfullName = user.DisplayName;
              loggedInUserEmail = user.EmailAddress;
          }
      }
  }
  </code></pre>
  
  <p>While the above works, I can't use any of those variables outside of the scope of the method, which isn't helpful.</p>
  
  <p>I tried the method below to just get the <code>DisplayName</code> but got errors due to <code>FindByIdentity</code> expecting a string (I don't have a string with the user's name - that's what I'm trying to find out!)</p>
  
  <pre><code>public string getUserFullName(object user)
  {
      user = UserPrincipal.FindByIdentity(ContextType.Domain, user);
      string loggedInUserDisplayName = user.DisplayName;
      return loggedInUserDisplayName ;
  }
  
  UserPrincipal loggedInUser = new UserPrincipal(ContextType.Domain); 
  // line above throws cannot convert from 'System.DirectoryServices.AccountManagement.ContextType' to 'System.DirectoryServices.AccountManagement.PrincipalContext'
  getUserDetails(loggedInUser); 
  </code></pre>
  
  <p>Is there a way to do this? Am I using the wrong library to achieve what I want? </p>
  
  <p>This is a web application using windows authentication, if that makes any difference.</p>
  
  <p>Thanks</p>