DotNet Mirror
  DNM facebook   DNM Google+   DNM Twitter   

How to Remove User from SharePoint Group programmatically

By Ashok Nalam on 28 May 2013 | Category: Sharepoint | Tagged: groups user delete remove 
Snippet covers how to delete SharePoint user from SharePoint group programmatically.
  Discuss Add Comment   |  
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 

The snippet shows, how to remove user from SharePoint group. "RemoveUserFromSPGroup" method accepts  3 parameters as SPSite object, LoginName of the user and Group name.

//Removes user from SPGroup
public static void RemoveUserFromSPGroup(SPSite site, string userLoginName, string groupName)
    //Executes this method with Full Control rights even if the user does not have Full Control
            using (SPWeb spWeb = site.RootWeb)
                    spWeb.AllowUnsafeUpdates = true;//Allows updating web
                    SPUser spUser = spWeb.EnsureUser(userLoginName);
			//check user and group exists in web
                    	if (spUser != null && CheckGroupExistsInSiteCollection(spWeb, groupName))
				SPGroup spGroup = spWeb.Groups[groupName];
				if (spGroup != null)
                catch (Exception)
                    //exception handling
                    spWeb.AllowUnsafeUpdates = false; //Even Exception occurs it set back to false
//checks group exists in site collection
private static bool CheckGroupExistsInSiteCollection(SPWeb web, string groupName)
  return web.SiteGroups.OfType<SPGroup>().Count(g => g.Name.Equals(groupName, StringComparison.InvariantCultureIgnoreCase)) > 0;

Method call :

SPSite currentSite = SPContext.Current.Site;
SPUser loginName = "Domain\LoginName";
RemoveUserFromSPGroup(currentSite,loginName,"Group Visitors")


Removes "Domain\LoginName" user from "Group Visitors" group


In the code we are using

  • SPSecurity.RunWithElevatedPrivileges - executes code with full control
  • AllowUnsafeUpdates to true - Because we are removing user from SPGroup so AllowUnsafeUpdates allow updates to the web.

  Discuss Add Comment    
Add rating Rate this resource  [Rated 5.00/5 by 1 people] 
About the Contributor
Member Since : 10 Dec 2012
Member Points (Level) : 9226  (Professional)
Location : INDIA
Home Page :
About : I am admin of this site.
Rate this resource
Add your Comment
Name Email WebSite
Captcha Refresh

Comments (0)
No comments found, click here to add comment.
cheap jordans|wholesale air max|wholesale jordans|wholesale jewelry|wholesale jerseys