How to add Users to a SharePoint Group in SharePoint 2013
Hello SharePointers,
In this article, I will give a simple code to add users to a SharePoint group programattically.Below is the code to add a user to the group using Server Side Object Model.
public static void AddUserToSharePoint Group( string spuser,string spgroup,string spurl)
{
string loginName = spuser;
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(spurl))
{
using (SPWeb web = site.OpenWeb())
{
try
{
web.AllowUnsafeUpdates = true;
// Check if User exists
SPUser spUser = web.EnsureUser(sploginName);
if (spUser != null)
{
SPGroup Group = web.Groups[spgroup];
if (Group != null)
{
spGroup.AddUser(spUser);
}
}
}
catch (Exception ex)
{
//Write to Log
Console.WriteLine(ex.Message);
}
finally
{
web.AllowUnsafeUpdates = false;
web.Close();
}
}
}
});
Console.WriteLine(“spuser add successfully”);
}
Ensure User is a method that checks whether the specified logon name belongs to a valid user of the SharePoint Site, and if the logon name does not already exist, it will add it to SharePoint Site.
Please read my article to know about Remove Users from SharePoint Group Programmatically in SharePoint 2013
Happy SharePointing 🙂