Other Posts in SharePoint

  1. Creating a SharePoint Site Programmatically
  2. Fix Access Denied Errors in SharePoint Search
  3. Web Page to Get Basic Information from SharePoint

Creating a SharePoint Site Programmatically

3/6/2009

I've been working with SharePoint at work... Working through the interface is simple, but I've been tasked with coming up with another side site that will allow us to remotely configure the server... Don't ask. Anyway, while attempting to discover how to programmatically create a site collection, I stumbled upon how to create a site:

   1: if (Request.HttpMethod == "POST")
   2: {
   3:     SPSecurity.RunWithElevatedPrivileges(delegate()
   4:     {
   5:         using (SPSite site = new SPSite("http://SITE"))
   6:         {
   7:             SPWebApplication webapp = site.WebApplication;
   8:             SPWeb web = site.OpenWeb();
   9:             web.AllowUnsafeUpdates = true;
  10:             web.Site.AllowUnsafeUpdates = true;
  11:             web.Webs.Add("Name", "name site", "", 1033, "STS#0", false, false);
  12:             web.Dispose();
  13:         }
  14:     });
  15: }

Note that the code above is going to need you to modify it a bit. But you need to first include a reference to Windows Sharepoint Services, add:

   1: using Microsoft.SharePoint;
   2: using Microsoft.SharePoint.Administration;
   3: using Microsoft.SharePoint.Utilities;

Then the code above will still crash on you... You're going to need to also make sure that in the web.config file that you set it to windows authentication and turn on impersonation... Oh and you need to run this as someone who has access to the database/is a farm administrator... But that's what the impersonation is for. Then and only then will it MAYBE run. You may have to sacrifice a goat to Microsoft... It seemed to work for me... Oh and if you want, you can modify the theme (STS#0 is just the default theme) but I've had a couple issues with setting some of their defaults for some reason. Anyway, hopefully my pain helps someone else out, so try it out, leave feedback, and happy coding.



Comments