Maro
Maro

Reputation: 2629

Extract group name from DirectoryEntry

when i use the code below to get list of groups i get a long string represent the group name

CN=group.xy.admin.si,OU=Other,OU=Groups,OU=03,OU=UWP Customers,DC=WIN,DC=CORP,DC=com

But i just want to get the group name which is in this case group.xy.admin.si

 public static List<string> GetGroups(DirectoryEntry de)
   {
       var memberGroups = de.Properties["memberOf"].Value;

       var groups = new List<string>();

       if (memberGroups != null)
       {
           if (memberGroups is string)
           {
               groups.Add((String)memberGroups);
           }
           else if (memberGroups.GetType().IsArray)
           {
               var memberGroupsEnumerable = memberGroups as IEnumerable;

               if (memberGroupsEnumerable != null)
               {
                   foreach (var groupname in memberGroupsEnumerable)
                   {

                       groups.Add(groupname.ToString());
                   }

               }
           }

       }
       return groups;
   }

Upvotes: 0

Views: 1826

Answers (1)

BartekB
BartekB

Reputation: 8660

There are two options here:

  • use distinguishedName you got to retrieve group object from AD, use its 'name' attribute
  • use regex to extract group name

pseudo-code for regular expression:

string Pattern = @"^CN=(.*?)(?<!\\),.*";
string group = Regex.Replace(groupname.ToString(), Pattern, "$1");
groups.Add(group);

Name can contain "," that is escaped by "\", so this regex should work fine even if you have groups named "Foo, Bar"

Upvotes: 3

Related Questions