简体   繁体   中英

Check if Active Directory Group exists in current container using C#

I want to create a new Active Directory Group.

This is my code:

PrincipalContext ctx = new PrincipalContext(ContextType.Domain, domain, container, userName, password);

GroupPrincipal oGroupPrincipal = new GroupPrincipal(ctx, userName);
DirectoryEntry entry = new DirectoryEntry("LDAP://" + domain, userName, password,AuthenticationTypes.Secure);

if (entry.Children.Find("CN=" + groupName) != null) {

}

if (!DirectoryEntry.Exists("LDAP://" + System.Configuration.ConfigurationManager.AppSettings["Domain"] + "/CN=" + groupName + "," + System.Configuration.ConfigurationManager.AppSettings["Container"]))
{

     oGroupPrincipal.Description = groupName;
     oGroupPrincipal.GroupScope = (System.DirectoryServices.AccountManagement.GroupScope)Enum.Parse(typeof(System.DirectoryServices.AccountManagement.GroupScope), groupScope);
     oGroupPrincipal.IsSecurityGroup = isSecurity;
     oGroupPrincipal.Save(ctx);
}

The Part that I am having trouble with is to see if the newly created group exists before creating it. At this stage my code returns that al the groups exists so I am unable to create a group

This is to check if group exists:

if (entry.Children.Find("CN=" + groupName) != null) {

}

but it gives an exception There is no such object on the server.

any help would be appreciated.

You seem to be under the (false) assumption that a entry.Children.Find() will do a recursive search through your entire directory - it does not do that.

So, either you need to bind to the actual container where that group should be located, and then check its immediate children for existence of your group:

DirectoryEntry entry = new DirectoryEntry("LDAP://YourServer/OU=SubOU,OU=TopLevelOU,dc=test,dc=com", userName, password,AuthenticationTypes.Secure);

try
{     
     DirectoryEntry childGroup = entry.Children.Find("CN=TestGroup2");
     // create group here
}
catch (DirectoryServicesCOMException exception)
{
    // handle the "child not found" case here ...
}

or then you need to do a directory search for your group which works recursively through your entire directory (and thus will be much slower , too):

// define root directory entry
DirectoryEntry domainRoot = new DirectoryEntry("LDAP://" + domain, userName, password,AuthenticationTypes.Secure);

// setup searcher for subtree and search for groups 
DirectorySearcher ds = new DirectorySearcher(domainRoot);
ds.SearchScope = SearchScope.SubTree;
ds.Filter = "(&(cn=TestGroup2)(objectCategory=group))";

var results = ds.FindAll();

if(results.Count <= 0)
{
   // group not found -> create
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM