I have a security group (pictured below) in active directory that has an e-mail address associated with it. How do I get the e-mail address of the group? The GroupPrincipal
object does not have any e-mail address properties on it.
This is how I am retrieving all the groups:
using (PrincipalContext context = new PrincipalContext(DirectoryContextType, Domain)) {
using (var groupSearcher = new GroupPrincipal(context)) {
using (var searcher = new PrincipalSearcher(groupSearcher)) {
foreach (GroupPrincipal group in searcher.FindAll()) {
//How do I get the e-mail address?
}
}
}
}
I just wanted to add this here because I think it might be helpful. The account management library is great for quickly doing things like resetting passwords on AD users or getting common properties. But it definitely doesn't have all of them. What I do is get the Underlying directory object, like so...
// Pretend you have a groupprincipal object called 'group'
// This will get all of the properties of that group object not accounted for in
// System.DirectoryServices.AccountManagement
DirectoryEntry groupDE = group.GetUnderlyingObject() as DirectoryEntry();
// We all know that a distro group in AD will have at least 1 email address.
// However, A
// security group will have 0, and since the mail property is of type
// PropertyValueCollection, if you try to access the first member of the collection
// and it has no length, an exception will be thrown. The following code
// accounts for this problem.
// Get the mail attribute of the AD object
PropertyValueCollection group_email_addresses = groupDe.Properties["mail"];
// Make sure there is at least one address
if (group_email_addresses.Count > 0){
// knowing that you have at least one address, you can access the first entry or
// loop and grab all entries on a property, depending on the appropriate use case
Console.WriteLine(group_email_addresses[0]);
}
// This concept can be applied to all Principal Objects. Just look for the // GetUnderlyingObject() method to get started!
If you want to do this from Account Management you will need to make a new class that exposes that property.
[DirectoryObjectClass("group")]
[DirectoryRdnPrefix("CN")]
public class GroupPrincipalsEx : GroupPrincipal
{
public GroupPrincipalsEx(PrincipalContext context) : base(context) { }
public GroupPrincipalsEx(PrincipalContext context, string samAccountName)
: base(context, samAccountName)
{
}
[DirectoryProperty("mail")]
public string EmailAddress
{
get
{
if (ExtensionGet("mail").Length != 1)
return null;
return (string)ExtensionGet("mail")[0];
}
set { this.ExtensionSet("mail", value); }
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With