As per this entry: Cloning a sharepoint rolegroup I'm trying to create a console application to copy a SharePoint group, including its permissions.
Based on the answer from Tjassens I've reached the following:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SharePoint;
namespace REGroupCopy
{
class Program
{
static void Main(string[] args)
{
using (SPSite spSite = new SPSite("http://dev"))
{
using (SPWeb spWeb = spSite.RootWeb)
{
// first we find the group that we want to clone
SPGroup group = spWeb.Groups["Test Group"];
// then we use this retreived group to get the roleassignments on the SPWeb object
SPRoleAssignment ass = spWeb.RoleAssignments.GetAssignmentByPrincipal(group);
string groupName = "Test Group 2"; // group to create
string groupDescription = "Group created by REGroupCopy";
string user = "michael";
spWeb.SiteGroups.Add(groupName, user, user, groupDescription);
SPGroup newGroup = spWeb.SiteGroups[groupName];
SPRoleAssignment roleAssignment = new SPRoleAssignment(newGroup);
//add role to web
spWeb.RoleAssignments.Add(roleAssignment);
spWeb.Update();
}
}
}
}
}
Unfortunately I don't think I'm understanding everything correctly. Specifically, I think these lines are incorrect, but I'm unsure what they should be:
string groupName = "Test Group 2"; // group to create
string groupDescription = "Group created by REGroupCopy";
string user = "michael";
spWeb.SiteGroups.Add(groupName, user, user, groupDescription);
I don't necessarily need somebody to come along and fix this for me (after all ,this is a learning exercise). Instead, could you please help me to understand where my thought process is falling down and what I need to learn to rectify this?
You have found the correct problem with your code. When you call the following method:
spWeb.SiteGroups.Add(groupName, user, user, groupDescription);
you forgot that the user should not be a string but an actual SPUser
object. If you get the SPUser
object you should be able to add the new group to the SPWeb/SPSite.
you can get the user object by using for instance:
SPUser spUser = spWeb.EnsureUser(loginName);