Retrieving Current Users E-mail Address from Active Directory

admin Last updated on: April 13, 2023

Retrieving Current Users E-mail Address from Active Directory

April 7th, 2009

I’ve seen several examples online of how to retrieve the logged in users e-mail address from Active Directory.  Every example I see involves taking the username (via System.Enviornment.UserName) and then doing an LDAP search for that user.

A faster and more effecient way is to take the current users Sid and do Sid Binding against Active Directory.  This allows you to skip the step of searching LDAP.  It also keeps you from having to do the work of making sure you’re getting the right user from the right domain.

public string GetEmail()
{
    //add using statement for System.Security.Principal
    //Retrieve Sid of currently logged in user
    WindowsIdentity user = WindowsIdentity.GetCurrent();
    SecurityIdentifier userSid = user.User;

    //Create LDAP path to user with Sid
    string adPath = String.Format(
        "LDAP://", userSid);

    //Create DE object
    DirectoryEntry sidBind = new DirectoryEntry(
        adPath,
        null,
        null,
        AuthenticationTypes.Secure);

    //retrieve e-mail address property
    if (sidBind.Properties.Contains("mail"))
    {
        return sidBind.Properties["mail"].Value.ToString();
    }
    else
    {
        return String.Empty;
    }
}

Related posts

Kèo chấp 0.5 là gì? Những điều cần lưu ý khi chơi kèo này

Kèo chấp 0.5 là gì? Những điều cần lưu ý khi chơi kèo này

Kèo chấp 0.5 là gì? Để hiểu rõ hơn về tỷ lệ cược này và có thể chơi cá...

Học cách giải Rubik 3×3 đảm bảo thành công chỉ trong 10 phút

Học cách giải Rubik 3×3 đảm bảo thành công chỉ trong 10 phút

Cách giải Rubik 3×3 là một kỹ năng không quá khó học, ngay cả người bình thường cũng có...

Select Top X

Select Top X

SQL: Select Top X

Mê mẩn với 1001+ hình play together đẹp nhất hiện nay

Mê mẩn với 1001+ hình play together đẹp nhất hiện nay

Play Together là một trò chơi giải trí thú vị với đồ họa xịn sò cùng nhiều tính năng...

IT Departments Even the best IT departments can use some outside help at times. Serk specializes in difficult technologies...

Windows Server 2008 High Availability Windows Server 2008 High Availability – Slide Deck Learn when to use and how...