Delete user from Site Collection

Title: How to delete a user from a site collection

Details: Some one asked me to post a sample of code to acheive the above subject. So, here is the code. However let me explain few things so that you can proceed and alter few things.

#1 you can run though the SPUserCollection that you can get from web.SiteUsers collection and find more than 1 person. In general case if it is only 1 user, then use the below code.

#2 do trip between web.Users Vs web.SiteUsers. SiteUsers is the SiteCollection users and web.user is the user object.

Code:

static void RemoveUserFromSiteCollectionByUserName(string siteUrl, string userName)
{
    using (SPSite siteCollection = new SPSite(siteUrl))
    {
        using (SPWeb web = siteCollection.OpenWeb())
        {
            SPUser user = web.SiteUsers[userName];

            try
            {
                if (!user.IsDomainGroup && !user.IsSiteAdmin)
                {
                    web.SiteUsers.Remove(user.LoginName);
                    web.Update();
                }
            }
            catch (Exception ex)
            { 
                // user not found
            }
        }
    }
}

Comments