mylifeinaminute.com

Creating a new SPWeb through Code

by liquidpooled on Aug.07, 2008, under .NET, Microsoft, Office, Sharepoint Server, Visual Studio 2005, Visual Studio 2008, Windows SharePoint Services

To create a new SPWeb (a new site or workspace) and add it to the navigation (Top and QuickLaunch), you can use the following snippet:


SPWeb newWeb;

newWeb = SPContext.GetContext(HttpContext.Current).Web.Webs.Add(strURL, //URL ("foo" would generate example.com/foo)
	strTitle, //Title
	strDescription, //Description
	(uint)1033, // English
	strTemplate, // Template type
	bUseUnique, // Use unique permissions?
	false); // Convert existing web?

newWeb.Navigation.UseShared = (someCondition) ? true : false;

newWeb.Update();

if (newWeb.Navigation.UseShared)
{
	Microsoft.SharePoint.Navigation.SPNavigationNode pNode = new Microsoft.SharePoint.Navigation.SPNavigationNode(newWeb.ParentWeb.Title, newWeb.ParentWeb.Url.Replace(newWeb.ParentWeb.Site.Url, string.Empty));
	Microsoft.SharePoint.Navigation.SPNavigationNode cNode = new Microsoft.SharePoint.Navigation.SPNavigationNode(newWeb.Title, strURL);
	newWeb.ParentWeb.Navigation.TopNavigationBar.AddAsLast(cNode);

	// add to quick launch
	Microsoft.SharePoint.Navigation.SPNavigationNodeCollection quickLaunch = newWeb.ParentWeb.Navigation.QuickLaunch;
	foreach (Microsoft.SharePoint.Navigation.SPNavigationNode node in quickLaunch)
	{
		if (node.Title == "Sites")
		{
			node.Children.AddAsLast(cNode);
			break;
		}
	}
}

newWeb.Dispose();
1 comment for this entry:
  1. Craig

    Nice. I mean, hideous, but nice. Should be so much simpler eh?

Leave a Reply

Looking for something?

Use the form below to search the site:

Still not finding what you're looking for? Drop a comment on a post or contact us so we can take care of it!

Visit our friends!

A few highly recommended friends...