Creating an application using the SharePoint Object Model to delete a site.


This entry is a walk-through on how to create a simple SharePoint Object Model application (often referred to as SharePoint OM or just OM).

First, open Visual Studio.NET 2003 on your development server that has WSS or SPSv2 installed.
Create a new C# Windows application.  Mine here is called DeleteSite.

We need to add a reference to Microsoft.SharePoint so that we can use it within this application.  To do this, access the Solution Explorer, expand References, right click and select Add Reference.  You will also see the choice to Add a Web Reference.  We will cover this option in a later blog entry.

In the Add Reference window, scroll down to the bottom.  You should see Windows SharePoint Services.  Select it, click Select (or just double-click) and you should see it in the list below.  Once you do, click OK.

Now we should add a using statement to make this component more accessible.  Simply go to the top of the CS and type using Microsoft.SharePoint;

Now create a textbox, a button and another textbox in the design view.
The first textbox we will use to type the http://server/sites/siteaddress URL. 
The second textbox will be used to log errors (you might make it multi-line). 
The button will be used to delete what is in the first textbox.

Double-click the button to take you to an automatically generated empty button1_Click function.
Populate that function with the following code:

private void button1_Click(object sender, System.EventArgs e)
{
      
using(SPSite mySite = new SPSite(this
.textBox1.Text))
      {
            
try
            
{
                  mySite.Delete();
            }

            
catch (Exception ex)
            {
                  
this
.textBox2.Text = ex.Message;
            }
      }
}

Then compile your app and test.

Note that when I use SPSite (or if I were using SPWeb) I do it within using.  This ensures that the SPSite resource is properly disposed. 
You could instead manually call  mySite.Dispose();   I like to instantiate SPSite and SPWeb inside using wherever possible to ensure proper cleanup.

It is also worth noting that whenever you do any specific operation that would actually require accessing SQL--you should be in a try block.
Declaring the new site object itself doesn't require SQL access, but accessing any information off of it or doing an operation would.

Skip to main content