Mark Kram
Mark Kram

Reputation: 5832

Getting Email address from Active Directory

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.

Upvotes: 2

Views: 12507

Answers (2)

A Ghazal
A Ghazal

Reputation: 2813

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"]); 

Upvotes: 2

Mark Kram
Mark Kram

Reputation: 5832

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

Upvotes: 6

Related Questions