2

How does one delete a site collection from the Recycling bin using C# CSOM? I can do it with the Cmdlet in Powershell like so:

Connect-SPOService https://tenant-admin.sharepoint.com
Remove-SPODeletedSite -Identity https://tenant.sharepoint.com/sites/deletedSite

But I want to do it in a Console application, any ideas?

2

1 Answer 1

2

The Tenant object allows you to delete the site from the recycling bin as well as deleting the site in the first place. This code example is an extension of the RemoveSite example to include removing the site from the recycling bin.

/// <summary>
/// Remove a site permanently
/// </summary>
/// <param name="adminUrl">The tenant admin URL</param>
/// <param name="targetUrl">site url</param>
internal void RemoveSite(string adminUrl, String targetUrl)
{
    // Connect to the site and tenant
    var ctx = new ClientContext(adminUrl);
    var tenant = new Tenant(ctx);
    // Delete the site and send it to the recycling bin
    var spoOperation = tenant.RemoveSite(targetUrl);
    ctx.Load(spoOperation);
    ctx.ExecuteQuery();
    Console.WriteLine("Time: " + DateTime.Now);
    WaitForOperation(spoOperation, "Deleting site")

    Console.WriteLine("Time: " + DateTime.Now);

    // Delete the site from the recycling bin
    spoOperation = tenant.RemoveDeletedSite(targetUrl);
    WaitForOperation(spoOperation, "Removing deleted site");
    Console.WriteLine("Time: " + DateTime.Now);
}

/// <summary>
/// Wait of an SpoOperation to complete
/// </summary>
private void WaitForOperation(SpoOperation operation, string operationName)
{
    while (!operation.IsComplete)
    {
        Thread.Sleep(2000);
        ctx.Load(operation);
        ctx.ExecuteQuery();
        Console.WriteLine($"{operationName} status: {(operation.IsComplete ? "waiting" : "complete")}");
    }
}

Tenant.RemoveDeletedSite

Tenant.RemoveDeletedSitePreferId

4
  • I'm getting an error on the first ExecuteQuery() Microsoft.SharePoint.Client.ServerException: 'Current site is not a tenant administration site.' Aug 23, 2017 at 22:20
  • Also getting the error on ClientRuntimeContext - inaccessible due to its protection level Aug 23, 2017 at 22:34
  • 1
    Updated the example, pass in the -admin.sharepoint.com site to the context instead of the site targeted for deletion.
    – Zach
    Aug 24, 2017 at 17:37
  • Getting 403 on the first ExecuteQuery() - maybe I need global tenant admin rights? Getting this error on RemoveDeletedSite: The property or field 'IsComplete' has not been initialized. Aug 25, 2017 at 15:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.