locked
Adding a security group to a site programatically C# RRS feed

  • Question

  • I have a bunch of security groups which I want to assign to sites programatically. I been looking for a code snippet for this without much luck. Any help will be appreciated!
    Tuesday, January 31, 2012 6:12 PM

Answers

  • using (SPSite site = new SPSite("http://server/sites/home/"))
    {
        SPWeb web = site.RootWeb;
        web.SiteGroups.Add("Some Group", web.SiteUsers[@"domain\user"], web.SiteUsers[@"domain\user"], "Some description");
        SPRoleAssignment ra = new SPRoleAssignment(web.SiteGroups["Some Group"]);
        ra.RoleDefinitionBindings.Add(web.RoleDefinitions["Contribute"]);
        web.RoleAssignments.Add(ra);
        web.Update();
    }
    


    Does this help?

    Note, this actually creates a group and then gives it permissions on a web.  You could just get the group if it already exists.

    • Marked as answer by Mark-AR Wednesday, February 1, 2012 2:38 AM
    Tuesday, January 31, 2012 8:33 PM

All replies

  • using (SPSite site = new SPSite("http://server/sites/home/"))
    {
        SPWeb web = site.RootWeb;
        web.SiteGroups.Add("Some Group", web.SiteUsers[@"domain\user"], web.SiteUsers[@"domain\user"], "Some description");
        SPRoleAssignment ra = new SPRoleAssignment(web.SiteGroups["Some Group"]);
        ra.RoleDefinitionBindings.Add(web.RoleDefinitions["Contribute"]);
        web.RoleAssignments.Add(ra);
        web.Update();
    }
    


    Does this help?

    Note, this actually creates a group and then gives it permissions on a web.  You could just get the group if it already exists.

    • Marked as answer by Mark-AR Wednesday, February 1, 2012 2:38 AM
    Tuesday, January 31, 2012 8:33 PM
  • "Some Group" would be the name of the group right? If I already have the name of the group in a variable, I just delete this line?:

    web.SiteGroups.Add("Some Group", web.SiteUsers[@"domain\user"], web.SiteUsers[@"domain\user"], "Some description");

    Thank you!
    Wednesday, February 1, 2012 2:48 AM