Prevent sites from being deleted with code

Problem:

Site Owners are deleting sites when they shouldn’t be. A governance process exists to approve the deletion of a site and should be used, but it’s not always happening. This causes documents and other information to be lost causing confusion when Users search for the deleted content. 

Solution:

Add an event receiver to prevent users from deleting a site.

Steps:

Open Visual Studio 2010 and create a new EventReceiver project

Point to the correct URL and set to farm solution

Select “Web Events” and check “A site is being deleted”

Add the following code to the “WebDeleting” method.

 public override void WebDeleting(SPWebEventProperties properties)
{

      try
      {
          properties.Cancel = true;
          properties.ErrorMessage = “Not Allowed!”;
      }

      catch (Exception ex)
      {
          properties.Cancel = true;
          properties.ErrorMessage = ex.Message.ToString();
      }
}

Change the scope of your feature to “Site” to include all sites in a site collection

Deploy your solution, navigate to site settings, and try to delete your site.


I am just using the standard error page which may work for you, but you can always create a custom error page if needed. I hope this helps you out!