Сохранить сайт как шаблон программно - Ошибка при создании файлов решения во временном каталоге

У меня есть требование, как, мне нужно создавать шаблоны сайтов программно. когда я пытаюсь сохранить сайт как шаблон программно, я получаю сообщение об ошибке ниже. Msgstr "Ошибка генерации файлов решения во временном каталоге". Я дал полный контроль над каталогом c:\windows\temp. И я использую ниже метод:

oWeb.SaveAsTemplate(templateName, templateTitle, tmplDesc, true);

(или же)

string solutionFileUrl = SPSolutionExporter.ExportWebToGallery(oWeb,templateName, templateTitle,tmplDesc,SPSolutionExporter.ExportMode.FullReuse,true);

сталкивается с той же проблемой.

я могу сохранить корневую сеть как шаблон как SPContext.Current.Web.SaveAsTemplate(templateName, templateTitle, tmplDesc, true); но мне нужно сохранить сайт как шаблон.

Ниже мой дамп журнала ULS

System.Runtime.InteropServices.COMException: список не существует. Страница, которую вы выбрали, содержит список, который не существует. Возможно, он был удален другим пользователем.0x81020026, StackTrace: по адресу Microsoft.SharePoint.SPListCollection.EnsureListsData(Guid webId, String strListName) в Microsoft.SharePoint.SPListCollection.ItemByInternalName(Guid webId, String listName.WWPP.Point) в Microsoft.Sp.ListViewWebPart.EnsureList() в Microsoft.SharePoint.WebPartPages.ListViewWebPart.EnsureListAndView(Boolean requireFullBlownViewSchema) в Microsoft.SharePoint.WebPartPages.ListViewWebPart.ShouldSerializeTitWWWWWW.Web.Wist Строка n, строка ns, ListViewWebPart o, логическое значение isNullable, логическое значение типа () (необходимо указать в Microsoft.Xml.Serialization.GeneratedAssembly.XmlSerializationWriterListViewWebPart.Write15_WebPart(объект o) в System.RuntimeMethodHandle.igot конструктор) в System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal (Object obj, Object[] para метров, Object[] arguments) в System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, связыватель Binder, параметры Object [], культура CultureInfo)
в System.Xml.Serialization.TempAssembly.InvokeWriter (отображение XmlMapping, XmlWriter xmlWriter, объект o, пространства имен XmlSerializerNamespaces, String encodingStyle, String id) в System.Xml.Serialization.XmlSerializer.S...... eritize xW (Xmlize) XW Объект o, пространства имен XmlSerializerNamespaces, String encodingStyle, String id) в Microsoft.SharePoint.WebPartPages.WebPart.SerializeXml (XmlWriter Writer, XmlSerializer xmls, Boolean shouldSerializeAll) в Microsoft.SharePoint.WebPartPerServiceServiceSW. Microsoft.SharePoint.WebPartPages.WebPart.WriteXmlAsUtf8(Boolean shouldExcludeSpecialProperties) в Microsoft.SharePoint.WebPartPages.SPWebPartManager.GetWebPartXml(WebPart WebPart, булевой shouldUTF8Encode, булевы shouldExcludeSpecialProperties, Boolean экспорт) в Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager.ExportWebPart(WebPart WebPart, Автор XmlWriter) в Microsoft.SharePoint.SPSolutionExporter... ....GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List 1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List 1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInWeb(String workflowTemplateName) в Microsoft.SharePoint.SPSolutionExporter.GenerateSolutionFiles() в Microsoft.SharePoint.SPSolutionExporter.ExportWebAsSolution() в веб-узле Майкрософт. Заголовок строки, описание строки, ExportMode exportMode, логическое includeContent, String workflowTemplateName, строка String......IONListUrl, Action`1 solutionPostProcessor, Boolean activSolution) в Microsoft.SharePoint.SPWeb.SaveAsTemplate(String strTemplateName, String strTemplateTcription String strTemplate, Логическое значение fSaveData) в TemplateIssueProject.ProjectTemplate.<> C__DisplayClass9.b__6() в Microsoft.SharePoint.SPSecurity.<> C__DisplayClass5.b__3() в Microsoft.SharePoint.Utilities.SecurityContext.RunAsProcess(CodeToRecurity.secure).RunWithElevatedPrivileges(WaitCallback secureCode, Object param) на микрофоне rosoft.SharePoint.SPSecurity.RunWithElevatedPrivileges(CodeToRunElevated secureCode) в TemplateIssueProject.ProjectTemplate.SaveTemplate(String webName, String templateName, String template... ...Title, String tmplDesc)
в TemplateIssueProject.ProjectTemplate.SiteCreation(String siteName) в TemplateIssueProject.TemplateIssewebpart.TemplateIssewebpart.btnSubmit_Click(Отправитель объекта, EventArgs e) в System.Web.UI.WebContebs.Wevent.ProcessRequestMain (логическое значение includeStagesBeforeAsyncPoint, логическое значение includeStagesAfterAsyncPoint)
в System.Web.UI.Page.ProcessRequest(Boolean includeStagesBeforeAsyncPoint, Boolean includeStagesAfterAsyncPoint)
в System.Web.UI.Page.ProcessRequest() в System.Web.UI.Page.ProcessRequest(контекст HttpContext) в ASP.WKPSTD_ASPX__1961116010.ProcessRequest(контекст HttpContext) в System.Web.HttpApplication.CttHApplication.CtionHebp.IExecut...... ionStep.Execute() в System.Web.HttpApplication.ExecuteStep(шаг IExecutionStep, логический и завершенный синхронно) в System.Web.HttpApplication.PipelineStepManager.ResumeSteps(исключительная ошибка) в System.Wepp. (Контекст HttpContext, AsyncCallback cb) в System.Web.HttpRuntime.ProcessRequestNotificationPrivate(IIS7WorkerRequest wr, контекст HttpContext) в System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper (Intntt.Text). Hosting.PipelineRuntime.ProcessRequestNotification (IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, Int32 flags) в System.Web.Hosting.Unsaf eIISMethods.MgdIndicateCompletio...... n (IntPtr pHandler, RequestNotificationStatus & messagesStatus)
в System.Web.Hosting.UnsafeIISMethods.MgdIndicateCompletion (IntPtr pHandler, RequestNotificationStatus & messagesStatus) в System.Web.Hosting.PipelineRuntime.ProcessRequestNotificationHelper (IntPtest. Intot. (IntPtr rootedObjectsPointer, IntPtr nativeRequestContext, IntPtr moduleData, флаги Int32)

System.NullReferenceException: ссылка на объект не установлена ​​на экземпляр объекта. в Microsoft.SharePoint.SPSolutionExporter.GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List 1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List 1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInFolderTree(папка SPFolder, SortedList 2 filesInFolder, List 1 webViews) в Microsoft.SharePoint.SPSolutionExporter.GetFilesInWeb(String workflowTemplateName) в Microsoft.SharePoint.SPSolutionExporter.GenerateSolutionFiles() в Microsoft.SharePoint.SPSolutionExporter.ExportWebAsSolution()

Ошибка приложения при доступе /SitePages/MyTaskPage.aspx, Ошибка = Ошибка при создании файлов решения во временном каталоге. в TemplateIssueProject.ProjectTemplate.SiteCreation(String siteName)
в TemplateIssueProject.TemplateIssewebpart.TemplateIssewebpart.btnSubmit_Click(Отправитель объекта, EventArgs e) в System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) в System.Web.UI.PageAsynfterAglegnSecureSecRequisionRequiseSecRequiseSecre

System.InvalidOperationException: Ошибка при создании файлов решения во временном каталоге. в TemplateIssueProject.ProjectTemplate.SiteCreation(String siteName)
в TemplateIssueProject.TemplateIssewebpart.TemplateIssewebpart.btnSubmit_Click(Отправитель объекта, EventArgs e) в System.Web.UI.WebControls.Button.RaisePostBackEvent(String eventArgument) в System.Web.UI.PageAsynfterAglegnSecureSecRequisionRequiseSecRequiseSecre

Пожалуйста, предложите / предоставить предложения.

С Уважением,

2 ответа

Решение

Приведенный ниже код используется для сохранения сайта в качестве шаблона (корневой уровень / дочерний сайт)

using System.Management;
using System.Management.Automation;
using System.Management.Automation.Runspaces;
Add Reference to your solution from the below path.

Reference Path: C:\Windows\winsxs\msil_system.management.automation_31bf3856ad364e35_7.1.7601.18071_none_a682d4c5c360dacf\System.Management.Automation.dll

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();

С уважением, Махеш http://sharepointchampion.blogspot.in/2014/05/save-site-as-template-programatically.html

Если вы добавили какие-либо поля через функцию, и в вашем поле есть Overwrite="FALSE", то экспорт сайта завершится неудачно. Вы должны использовать Overwrite, только если вам нужно установить TRUE, так как по умолчанию FALSE.

Это похоже на ошибку SharePoint.

Вы можете увидеть этот атрибут в ваших журналах ULS.

Другие вопросы по тегам