User Tools

Site Tools


Web Sites (SPWeb) in SharePoint 2010

Obtain the current root web:

SPWeb web = SPContext.Current.Site.RootWeb;

Redirect to another page if the current user is not the site admin:

if (!SPContext.Current.Web.CurrentUser.IsSiteAdmin)
    Response.Redirect(SPContext.Current.Web.Url + "/_layouts/AccessDenied.aspx", false);

Redirect to the current page (a loopback):


Set some properties of an SPWeb:

web.Title = "My Website";
web.SiteLogoUrl = "/_layouts/15/Images/logo.jpg";

Populate a drop-down list with a list of webs available for the current user:

public void PopulateWebsites()
    // Get SPWeb object representing the current web.
    SPWeb web = SPContext.Current.Web;
    // Get collection of subwebs the current user has permissions to see.
    SPWebCollection subwebs = web.GetSubwebsForCurrentUser();
    // Loop through the subweb collection.
    foreach (SPWeb subweb in subwebs)
            ddlSites.Items.Add(new ListItem(subweb.Title, subweb.Url));
            if (subweb != null)

Create a child web:

string siteUrl = SPContext.Current.Site.Url;
Guid webId = SPContext.Current.Web.ID;
    using (SPSite site = new SPSite(siteUrl))
        using (SPWeb web = site.OpenWeb(webId))
            CreateSubweb(web, "testweb", "New Test Web",
                "This is the new test web", "WIKI#0", "Test web comments...");
private void CreateSubweb(SPWeb parentWeb, string webUrl, string webTitle, 
    string webDesc, string webTemplate, string comments)
    bool UseUniquePermissions = false;
    SPWebCollection subsites = parentWeb.Webs;
    using (SPWeb newWeb = subsites.Add(webUrl, webTitle, webDesc, 
        parentWeb.RegionalSettings.LocaleId, webTemplate, UseUniquePermissions, false))
        // Set master pages.
        newWeb.MasterUrl = "/_catalogs/masterpage/MyMasterPage.master";
        newWeb.CustomMasterUrl = "/_catalogs/masterpage/MyMasterPage.master";
        // Set navigation.
        newWeb.QuickLaunchEnabled = false;
        newWeb.TreeViewEnabled = true; 
        newWeb.Navigation.UseShared = false;
        // Set the home page.
        SPFolder rootFolder = newWeb.RootFolder;
        rootFolder.WelcomePage = siteUrl;
        // Add properties
        AddProperty(newWeb, "MyComments", comments);
        // Associate the same owner group for the new site as for the parent site.
        newWeb.AssociatedOwnerGroup = parentWeb.AssociatedOwnerGroup;
        // Confirm updates.
// Add a property entry
private void AddProperty(SPWeb web, string key, string val)
    web.Properties[key] = val;
    web.AllProperties[key] = val;
notes/sharepoint2010/spweb.txt · Last modified: 2020/08/26 (external edit)