SharePoint: Deleting a site with subsites programmatically

This is a classic SharePoint stumble: You want to delete a site (SPWeb), so you think “I’ll just use the Delete method. Obviously!” as anyone would. A few moments later and you’re staring at this obstinate and unshiftable error message:

Microsoft.SharePoint.SPException : Error deleting Web site “/web”. You can’t delete a site that has subsites.

Eventually you resign yourself to having to write some form of recursive function to delete every subsite’s subsite’s subsites one by one.

*sigh*

So let me make your life a little easier. Stick this static class in your reusable library of helpful classes (everyone’s got one), and forget about the problem forever:

public static class SPWebFix
{
    /// <summary>
    /// Deletes the Web site, optionally forcing the deletion of subsites
    /// </summary>
    /// <param name="web">The site to delete</param>
    /// <param name="force">Forcing deletion causes the site to be deleted even if it has subsites</param>
    /// <returns>The total number of sites deleted</returns>
    public static int Delete(this SPWeb web, bool force)
    {
        if (force || web.Webs.Count == 0)
        {
            // Call the recursive function
            return deleteWeb(web);
        }
        else
        {
            // Return 0 to indicate that this site was not deleted.
            return 0;
        }
    }

    private static int deleteWeb(SPWeb web)
    {
        int sitesDeleted = 1;

        foreach (SPWeb subWeb in web.Webs)
        {
            sitesDeleted += deleteWeb(subWeb);
        }

        web.Delete();
        web.Dispose();

        return sitesDeleted;
    }
}

Now whenever you want to recklessly delete a site and all its subsites, simply call the extension method version with the ‘force’ flag set to true:

deleteThisWeb.Delete(true);

That’s one tiny problem fixed.Smile