环境:Windows Server 2012,SharePoint 2013,Visual Studio 2013
页面上创建子站点,点击网站右上角的小齿轮→选择网站内容→拉到底部,点击new subsite,进到建站的页面,填完信息点提交就可以了。
那么,我们怎么用代码创建一个Web呢?
首先,我们需要一个网站模板(wsp),有需要的,请参考SharePoint 2013 网站模板打包和根据模板建站。
然后,在代码中调用Add添加一个站点就可以了。下面直接上代码,不废话。
Webs.Add() 介绍
// 摘要:
// Creates a Web site object with the specified site-relative URL, title, description,
// locale ID, and site definition or site template object.
//
// 参数:
// strWebUrl:
// A string that contains the new Web site URL relative to the root Web site
// in the site collection. For example, to create a Web site at http://MyServer/sites/MySiteCollection/MyNewWebsite,
// specify MyNewWebsite, or to create a Web site one level lower at http://MyServer/sites/MySiteCollection/Website/MyNewWebsite,
// specify Website/MyNewWebsite.
//
// strTitle:
// A string that contains the title.
//
// strDescription:
// A string that contains the description.
//
// nLCID:
// An unsigned 32-bit integer that specifies the locale ID.
//
// WebTemplate:
// An Microsoft.SharePoint.SPWebTemplate object that represents the site definition
// or site template.
//
// useUniquePermissions:
// true to create a subsite that does not inherit permissions from another site;
// otherwise, false.
//
// bConvertIfThere:
// true to convert an existing folder of the same name to a SharePoint site.
// false to throw an exception that indicates that a URL path with the specified
// site name already exists.
//
// 返回结果:
// An Microsoft.SharePoint.SPWeb object that represents the Web site.
public SPWeb Add(string strWebUrl, string strTitle, string strDescription, uint nLCID, SPWebTemplate WebTemplate, bool useUniquePermissions, bool bConvertIfThere);
代码
using Microsoft.SharePoint;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace JobTest
{
class CreateSubWeb
{
/// <summary>
/// 创建Web
/// </summary>
/// <param name="spWeb">父站点</param>
/// <param name="url">子站点URL</param>
/// <param name="title">子站点标题</param>
/// <param name="desc">子站点描述</param>
/// <param name="lcid"></param>
/// <param name="template">网站模板名称</param>
public void CreateSubWeb(SPWeb spWeb, string url, string title, string desc, string lcid, string template)
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
try
{
//根据传进来的网站模板名称,拿到模板站
SPWebTemplate CustomTemplate = null;
SPWebTemplateCollection subWebTemplate = spWeb.GetAvailableWebTemplates(Convert.ToUInt32(lcid));
bool hasflag = false;
foreach (SPWebTemplate temp in subWebTemplate)
{
if (temp.Title.Contains(template))
{
CustomTemplate = temp;
hasflag = true;
break;
}
}
if (hasflag)
{
//建站
SPWeb newWeb = spWeb.Webs.Add(url, title, desc, Convert.ToUInt32(lcid), CustomTemplate, false, false);
}
}
catch (Exception ex)
{
//write to log
}
});
}
}
}