Question

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?

Was it helpful?

Solution

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

Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange
scroll top