Search code examples
c#.netsharepoint-onlinecsom

Remove user from SharePoint site in C#


I need to remove users from SharePoint site collection in C#/.NET. Here is the link for PowerShell code, but I need to write it in C#. https://learn.microsoft.com/en-us/sharepoint/remove-users

The below code is not working.

 private void RemoveUser(String user)
 {
    using (SPSite sps = new SPSite("http://serverName"))
            {
                using (SPWeb spWeb = sps.RootWeb)
                {
                    SPUserCollection spuc = sps.RootWeb.AllUsers;
                    spuc.Remove(user);
                }
            }
        }

Solution

  • I have one SharePoint site named sridemosite with members like below:

    From the SharePoint Admin Center:

    enter image description here

    From the SharePoint Portal:

    enter image description here

    To remove a user from this SharePoint site collection in .NET, I used the below code:

    using System;
    using System.Linq;
    using System.Security;
    using Microsoft.SharePoint.Client;
    
    namespace CSOMAuthentication
    {
        class Program
        {
            static void Main(string[] args)
            {
                // Provide Site URL
                string SiteURL = "https://xxxxxxxxxxx.sharepoint.com/sites/sridemosite";
                string Environmentvalue = "o365";
                string username = "[email protected]";
                string password = "xxxxxxxxxxx";
                AuthenticateUser(new Uri(SiteURL), Environmentvalue, username, password);
            }
    
            private static void AuthenticateUser(Uri TargetSiteUrl, string Environmentvalue, string username, string password)
            {
                try
                {
                    // Based on the environmentvalue provided it execute the function.
                  if (string.Compare(Environmentvalue, "o365", StringComparison.OrdinalIgnoreCase) == 0)
                    {
                        ClientContext Context = O365LogOn(username, password, TargetSiteUrl);
    
                        Group oGroup = Context.Web.SiteGroups.GetByName("sridemosite Members");
    
                        // Get user using Logon name
                        User oUser = Context.Web.EnsureUser("[email protected]");
    
                        Context.Load(oUser);
                        Context.ExecuteQuery();
    
                        // Remove user from the group
                        oGroup.Users.RemoveByLoginName(oUser.LoginName);
                        
                        Context.ExecuteQuery();         
                    }  
                }
                catch (Exception ex)
                {
                    // log error               
                }
            }
    
            private static ClientContext O365LogOn(string userName, string password, Uri url)
            {
                ClientContext clientContext = null;
                ClientContext ctx = null;
                try
                {
                    clientContext = new ClientContext(url);
    
                    // Condition to check whether the user name is null or empty.
                    if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
                    {
                        SecureString securestring = new SecureString();
                        password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));
                        clientContext.Credentials = new SharePointOnlineCredentials(userName, securestring);
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
                        clientContext.ExecuteQuery();
                    }
                    ctx = clientContext;
                }
                finally
                {
                    if (clientContext != null)
                    {
                        clientContext.Dispose();
                    }
                }
                return ctx;    
            }
        }
    }
    

    Response:

    enter image description here

    To confirm that, I checked the same in both Portals where the Devi user removed successfully from site collection like below:

    From the SharePoint Admin Center:

    enter image description here

    From the SharePoint Portal:

    enter image description here

    References:

    Remove User From Site Group in SharePoint using CSOM - Code SharePoint

    Connect to SharePoint Online, On premise and Extranet using CSOM - Code SharePoint