Setting site collection sharing by code

Introduction

Set the site collection sharing (capabilities) properties in SharePoint Online by using clientside code.

Sharing Capabilities

With SharePoint Online you can set the “Sharing properties” of a site collection to one of the following 3 properties.

  • Don’t allow sharing outside your organization
  • Allow external users who accept sharing invitations and sign in as authenticated users
  • Allow both external users who accept sharing invitations and anonymous guest links

You set this by going to your SharePoint online tendant site and use the “Share” button in the Site Collection overview. You get this screen

scSharing

Code

You can also set this option by code by using the method ‘GetSitePropertiesByUrl()’ that returns Microsoft.Online.SharePoint.TenantAdministration.SiteProperties object.

Note: There is an other method called ‘GetSiteProperties()’ which will not work since it returns a ‘SPOSitePropertiesEnumerable’ object.

See all the possible options for Microsoft.Online.SharePoint.TenantManagement.SharingCapabilities here.

CSOM sample.

using Microsoft.Online.SharePoint.TenantAdministration;
using Microsoft.Online.SharePoint.TenantManagement;

...
using (var tenantContext = TokenHelper.GetClientContextForApp(new Uri(TenantSite)))
{
	// Get properties of new Site Collection
	SiteProperties siteprops = tenant.GetSitePropertiesByUrl("https://yourName.sharepoint.com/", true);
	tenantContext.Load(siteprops);
	tenantContext.ExecuteQuery();

	// Set the Sharing option of the new site collection
	siteprops.SharingCapability = SharingCapabilities.ExternalUserSharingOnly;
	siteprops.Update();
	tenantContext.ExecuteQuery();
}

With a little effort it can be easliy converted to a JavaScript or PowerShell based script.

Share Your Thoughts