Friday, August 31, 2007
How to create a site programmatically in WSS 3.0
As part of a project I am working on, I need to make a lot of sharepoint websites based off the same customized template. I'm obviously not going to sit there and click over and over, so here's how to do it in C#, I hosted this in an ASPX page and ran it on the server. SPSite newSite = new SPSite("http://server/siteurl"); SPWeb newWeb = newSite.OpenWeb(); newWeb.AllowUnsafeUpdates = true ; newWeb.Update(); SPWebCollection subsites = newWeb.Webs; SPWeb newSubWeb = subsites.Add("siteurl", "sitetitle", "sitedescription", 1033, "template.stp", true, false); remember to add a reference to 'Windows SharePoint Services' and add 'using' lines for: using Microsoft.SharePoint; using Microsoft.SharePoint.Utilities; The AllowUnsafeUpdates part of the code allows you to do your method in the GET section of the code, for example Page_Load, I believe you might not need this if you do your work in a postback, ie by adding a button to click. To create a custom template, I simply created a website, customized it, and went to Site Actions -> Site Settings then under look and feel clicked "Save site as template". When you fill out that page it is important to take note of the filename you give it! As this is used in the code above. I called mine BWJob, so my template was BWJob.stp. If you forget this name, you can find it in the Site Template gallery. If you want to use a default template, refer to Todd Baginski's blog, he has a list of what to write in the template section. This information is also available in C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\1033\XML\WEBTEMP.XML - it follows the strucutre of "Template Name#Configuration ID" so Team Site is "STS#0" instead of "template.stp". This method worked well for me.