How to Remove Users from SharePoint Group Programmatically in SharePoint 2013

Hello SharePointers,

In this article, I will give a simple code to remove users from a SharePoint group programatically.Below is the code to remove from user to the group using Server Side Object Model.

public static void AddRemovefromSharePoint 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.RemoveUser(spUser);
spGroup.Update();

}

}

}

catch (Exception ex)

{

//Write to Log

Console.WriteLine(ex.Message);

}

finally

{

web.AllowUnsafeUpdates = false;

web.Close();

}

}

}

});

                Console.WriteLine(“spuser Removed 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 Add Users to a SharePoint Group in SharePoint 2013.

Happy SharePointing 🙂

Leave a Reply

Your email address will not be published.