I want to import the Sitecore packages in Sitecore through code. Is there way to do this?
3 Answers
Here is a nice blog post from Akshay Sura describing how to export and import packages:
Code for import is:
using (new SecurityDisabler())
{
using (new ProxyDisabler())
{
using (new SyncOperationContext())
{
IProcessingContext context = new SimpleProcessingContext();
IItemInstallerEvents events = new DefaultItemInstallerEvents(new BehaviourOptions(InstallMode.Overwrite, MergeMode.Undefined));
context.AddAspect(events);
IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true);
context.AddAspect(events1);
Sitecore.Install.Installer installer = new Sitecore.Install.Installer();
installer.InstallPackage(MainUtil.MapPath("INSERT PACKAGE PATH INCLUDING THE FILE NAME"), context);
}
}
}
Your question did not specify which language the code needed to be written in, so here is an example in PowerShell.
PS master:\> Install-Package -Path YourPackageName.zip -InstallMode Merge -MergeMode Merge
Unless you have a really good reason to use C# code to install the packages, I would recommend you use Sitecore PowerShell Extensions (SPE).
Check out the book for more details: https://doc.sitecorepowershell.com/appendix/commands/Install-Package.html
You can use Sitecore API to import the packages. You can use the code like
using (new ProxyDisabler())
{
using (new SyncOperationContext())
{
IProcessingContext context = new SimpleProcessingContext();
IItemInstallerEvents events = new DefaultItemInstallerEvents(new BehaviourOptions(InstallMode.Overwrite, MergeMode.Undefined));
context.AddAspect(events);
IFileInstallerEvents events1 = new DefaultFileInstallerEvents(true);
context.AddAspect(events1);
Sitecore.Install.Installer packageInstaller = new Sitecore.Install.Installer();
packageInstaller.InstallPackage(MainUtil.MapPath("exact path for package with file name"), context);
}
}
}
Additionally you can use Sitecore API to export the package also.