Friday, December 4, 2020

How to add and remove user from site collection admins in Sharepoint Online using CSOM

Using the following code you may add user to site collection admins in Sharepoint Online via CSOM:

var adminContext = ...; // ClientContext for https://{tenant}-admin.sharepoint.com
string siteUrl = "https://{tenant}.sharepoint.com/sites/foo";
string loginName = ...; // user name which should be added to site collection admins
var tenant = new Tenant(adminContext);
tenant.SetSiteAdmin(siteUrl, loginName, true);
adminContext.ExecuteQueryRetry();

If you need to remove user from site collection admins use the following code:

var adminContext = ...; // ClientContext for https://{tenant}-admin.sharepoint.com
string siteUrl = "https://{tenant}.sharepoint.com/sites/foo";
string loginName = ...; // user name which should be added to site collection admins
var tenant = new Tenant(adminContext);
tenant.SetSiteAdmin(siteUrl, loginName, false);
adminContext.ExecuteQueryRetry();

(the difference is only that you need to pass false in tenant.SetSiteAdmin() method). Hope it will help in your work.

No comments:

Post a Comment