Getting Email address from Active Directory

11,169

Solution 1

Thanks to Davide Piras who send me this link, I found a suitable solution:

Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')

Dim dc As PrincipalContext = New PrincipalContext(ContextType.Domain, "DomainName")
Dim adUser As UserPrincipal = UserPrincipal.FindByIdentity(dc, a(1))
Dim Email As String = adUser.EmailAddress

Solution 2

This code works for me.. Reference to System.DirectoryServices.AccountManagement

   static string GetADUserEmailAddress(string username)
    {
        using (var pctx = new PrincipalContext(ContextType.Domain))
        {
            using (UserPrincipal up = UserPrincipal.FindByIdentity(pctx, username))
            {
                return up != null && !String.IsNullOrEmpty(up.EmailAddress) ? up.EmailAddress : string.Empty;
            }
        }
    }

to use it:

lblEmail.Text = GetADUserEmailAddress(Request.ServerVariables["AUTH_USER"]); 
Share:
11,169
Mark Kram
Author by

Mark Kram

Child of God, Husband, Father and Coder in that order.

Updated on June 04, 2022

Comments

  • Mark Kram
    Mark Kram almost 2 years

    All --

    I am able to retieve the FullName value I am trying to retrieve an email address from Active Directory but using the following code in my ASP.Net Web Forms project that is using Windows Authentication:

    Dim wi As System.Security.Principal.WindowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent()
    Dim a As String() = wi.Name.Split(New Char() {"\"c}) '' Context.User.Identity.Name.Split('\')
    
    Dim ADEntry As System.DirectoryServices.DirectoryEntry = New System.DirectoryServices.DirectoryEntry(Convert.ToString("WinNT://" + a(0) + "/" + a(1)))
    Dim Name As String = ADEntry.Properties("FullName").Value.ToString()
    Dim Email As String = ADEntry.Properties("mail").Value.ToString()
    

    when I get to the line of code where I'm try to retrieve the email address I get an "Object reference not set to an instance of an object." error. I have tried using EmailAddress, E-Mail. I think the problem is that I am simply using the wrong keyword. I am able to retrieve the FullName value.