Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create Active Directory Group using C#

I am creating an Web app for managing an Active Directory. I want to create a group in a certain container.

var groups = new List<Models.Group>();

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

GroupPrincipal oGroupPrincipal = new GroupPrincipal(ctx);
oGroupPrincipal.Description = mGroup.GroupName;
oGroupPrincipal.GroupScope = mGroup.GroupScope;
oGroupPrincipal.IsSecurityGroup = mGroup.IsSecurity;
oGroupPrincipal.Save();

but I get the following error:

Cannot implicitly convert type 'string' to System.DirectoryServices.AccountManagement.GroupScope?'

I am not sure how to handle this. How should I convert the GroupScope into an object GroupScope while it is a object string in my list?

I also got this error:

SamAccountName or Name must be assigned to a newly-created Principal object in this store > prior to saving.

like image 231
Gericke Avatar asked Sep 06 '25 03:09

Gericke


2 Answers

Group scope is an enum with values of local, global and universal, it looks like you haven't cast the incoming value.

Try setting this to a static value:

oGroupPrincipal.GroupScope = System.DirectoryServices.AccountManagement.GroupScope.Local;

If this clears the error then try parsing your incoming string:

oGroupPrincipal.GroupScope = (System.DirectoryServices.AccountManagement.GroupScope)Enum.Parse(typeof(System.DirectoryServices.AccountManagement.GroupScope),value);
like image 96
Andy March Avatar answered Sep 07 '25 21:09

Andy March


Try

GroupPrincipal oGroupPrincipal = new GroupPrincipal(ctx, samAccountName);

And

oGroupPrincipal.Save(ctx);

Code samples for Active Directory -

http://www.codeproject.com/Articles/18102/Howto-Almost-Everything-In-Active-Directory-via-C#
Active Directory With C#

like image 22
Aseem Gautam Avatar answered Sep 07 '25 21:09

Aseem Gautam