Search code examples
c#principalcontext

Get Email of an AD Group using C#


I am trying to get the email of an AD group using C#, below is the code that I have.

using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain, ADDomain))
{
    using (GroupPrincipal grp = GroupPrincipal.FindByIdentity(ctx, IdentityType.Name, ADGroup))
    {
        var sams = from x in grp.GetMembers(true) select new { x.SamAccountName, };
        var users = from sam in sams.Distinct()
                    let usr = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, sam.SamAccountName)
                    select new { usr.SamAccountName, usr.DisplayName, usr.EmailAddress };
    }
}

May I know how can I assign usr.EmailAddress to a variable?


Solution

  • You are creating an anonymous type, which means that the properties will have the same name as what you assigned in the select .Assuming that there is only meant to be one item in that list you can use this.

    var result = users.SingleOrDefault()
    if (result != null)
    {
        var emailAddress = result.EmailAddress
    }