Saturday, July 20, 2013

Save Site as template using Object Model

public void savesiteastemplate(string webname)
{
 string templatename;
string templatetitle;
string templatedesc;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite _site = new SPSite(SPContext.Current.Site.ID))
{
_site.AllowUnsafeUpdates =true;
using (SPWeb oweb = _site.RootWeb)
{
SPWebCollection _webcol = _site.AllWebs;
oweb.AllowUnsafeUpdates = true;
foreach (SPWeb _web in _webcol)
{
if (string.IsNullOrEmpty(txtwebname.Text))
{
msg = "Enter the name of a web";
}
else if (_web.Name.ToLower() == txtwebname.Text.ToLower())
{
templatetitle = _web.Name + "Template";
templatename = _web.Name + "Template";
_web.SaveAsTemplate(templatename, templatetitle, templatedesc,false);
msg = "Template Saved Successfully";
txtwebname.Text = "";
break;
}
else
{
msg = "web is not available";
}
}
oweb.AllowUnsafeUpdates= false;
PnlMain.Controls.Add(new LiteralControl(msg));
_site.AllowUnsafeUpdates =false;
}
}
});
}
catch (Exception ex )
{
lblmsg.Text = ex.Message;
}
}


Where
strTemplateName
Type: System.String
The name to use for the template on the Create form and also for the file name of the solution package (.wsp) that contains the template. If a solution package with the same file name already exists, a numeric suffix is added to the name when the solution file name is formed. For example, if you pass "Test", the method tries to create a template file named "Test.wsp". If that name is taken, it tries "Test2.wsp". If that name is in use, it tries "Test3.wsp" and so on.
strTemplateTitle
Type: System.String
A string that contains the display name of the site template.
strTemplateDescription
Type: System.String
A string that contains the description of the site template.
fSaveData
Type: System.Boolean
true if data on the website is saved as part of the site template; otherwise, false.