Here is the C# code using this we can add or remove user from SharePoint group:
Using C# SSOM - server object model
SPWebApplication g_WebApp;
SPWeb g_Web;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
SPSite site = new SPSite(“<siteUrl>”);
//siteName = "Payroll";
g_Web = site.OpenWeb(“<siteName>”);
g_WebApp = g_Web.Site.WebApplication;
g_WebApp.FormDigestSettings.Enabled = true;
g_Web.AllowUnsafeUpdates = true;
SPUser user = g_Web.AllUsers[“<username>”];
SPMember member = g_Web.SiteUsers[“<requestedBy>”];
if (user != null)
{
SPGroupCollection grpCollection = g_Web.SiteGroups;
bool isExists = IsGroupExists(grpCollection,
“GroupName”);
if (!isExists && “Add” == Action.Add)
{
g_Web.SiteGroups.Add(“GroupName”, member, user,
Constants.Messages.DESCRIPTION);
g_Web.AssociatedGroups.Add(g_Web.SiteGroups
[“GroupName”]);
g_Web.Update();
SPRoleAssignment assignment = new SPRoleAssignment(
g_Web.SiteGroups[“GroupName”]);
SPRoleDefinition _role = g_Web.RoleDefinitions
[Constants.PermissionLevel.CONTRIBUTE];
assignment.RoleDefinitionBindings.Add(_role);
g_Web.RoleAssignments.Add(assignment);
}
else
{
SPGroup group = g_Web.SiteGroups[“GroupName”];
if (group != null)
{
if (“Add”.Equals(Action.Add))
{
group.AddUser(user);
}
else if (“Remove”.Equals(Action.Remove))
{
group.RemoveUser(user);
}
group.Update();
}
}
}
}
}
g_Web.Update();
g_WebApp.FormDigestSettings.Enabled = true;
});
}
catch
{
throw;
}
finally
{
g_Web.AllowUnsafeUpdates = false;
}
private bool IsGroupExists(SPGroupCollection grpCollection,
string groupName)
{
bool isExists = false;
foreach (SPGroup group in grpCollection)
{
if (group.Name.Equals(groupName))
{
isExists = true;
break;
}
}
return isExists;
}
}
public enum Action
{
Add,
Remove
}
Reference URL:
Add and Remove User into SharePoint group using SharePoint Server Object Model
Using C# CSOM - client object model:
ClientContext client = new ClientContext(“http://SiteUrl”);
client.ExecuteQuery();
Web website = client.Web;
client.Load(website, w => w.AllProperties, w => w.SiteGroups, w => w.SiteUserInfoList, w => w.Webs,w => w.Title);
client.ExecuteQuery();
GroupCollection groupCollection = website.SiteGroups;
client.Load(groupCollection, groups => groups.Include(grps => grps.Users, grps => grps.Title));
client.ExecuteQuery();
User user;
foreach (Group group in groupCollection)
{
if (group.Title.Equals(“GroupName”))
{
UserCreationInformation userInfo = new UserCreationInformation();
userInfo.LoginName = “UserName”;
if (“Add”)
{
user = group.Users.Add(userInfo);
group.Users.AddUser(user);
}
else if (“Remove”)
{
user = group.Users.GetByLoginName(“UserName”);
group.Users.Remove(user);
}
group.Update();
website.Update();
client.ExecuteQuery();
}
}
Code reference is here:
Add and remove User into SharePoint group Using Client Object Model