Save Site As Template Programatically in SharePoint

4 comments
Hi All,

Below example demonstrates how to Save  "SITE AS TEMPLATE."

I would like to write what are the scenarios i have tried, finally how it was achieved...

1 st Trial:

using (SPSite oSite = new SPSite(siteID, SPContext.Current.Site.SystemAccount.UserToken))
                {
                    using (SPWeb oWeb = oSite.OpenWeb(webName))
                    {
                     SPUserSolution solution =oSite.Solutions.Cast<SPUserSolution>().FirstOrDefault(s =>                                                                                         s.Name.StartsWith(templateName));
                        if (solution == null)
                            oWeb.SaveAsTemplate(templateName, templateTitle, tmplDesc, true);
                    }
                }

Error: Error Generating Solution files in directory.Google said ki  , provide admin (App Pool account) full permission on c:\Windows\Temp (or) c:\Temp. But No Use. Those folders are read-only folders. 2nd Trail: tried the below method,


public static string ExportWebToGallery(
 SPWeb web,
 string solutionFileName,
 string title,
 string description,
 SPSolutionExporter.ExportMode exportMode,
 bool includeContent
)
still same issue. At Final, we have achieved this by using PS + SOM. Please find the below code snippet.
using System.Management;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
Add below Reference to your solution
Reference Path:
C:\Windows\winsxs\msil_system.management.automation_31bf3856ad364e35_7.1.7601.18071_none_a682d4c5c360dacf\System.Management.Automation.dll
 
public void SiteAsTemplate(Template objTemplate)
{
string FullWebUrl =string.Empty;
RunspaceInvoke oRunSpaceInvoke = new RunspaceInvoke();
FullWebUrl = SPContext.Current.Site.Url + "/" + objTemplate.strWebName;
strScriptToSaveTemp = 
@"Add-PSSnapin Microsoft.SharePoint.PowerShell ; Set-ExecutionPolicy -ExecutionPolicy RemoteSigned ;" +"$oWeb = Get-SPWeb \"" + FullWebUrl + "\" ;                                                                                                                                                          $oWeb.SaveAsTemplate(\"" + objTemplate.strTemplateTitle + "\",\"" + objTemplate.strTemplateName +"\",\"" + objTemplate.strTemplateDesc + "\",1) \n"
oRunSpaceInvoke.Invoke(strScriptToSaveTemp).ToString();
}
I am passing all my parameters to this method as an object. This method will work for all root level web and Sub sites also.

Related Post

4 comments:

  1. Good Post....!!!

    ReplyDelete
  2. Thanks you....So helpfull !!

    ReplyDelete
  3. Updated the script which will create templates with spaces between text.

    Thanks,
    Mahesh

    ReplyDelete