Valid for Sitecore
5.3
Publishing an Item Programmatically
Sitecore versions: tested with 5.3.0.
The Problem:
Our code needs to publish an item programmatically.
1. The Solution
Use the code below:
using System;
using Sitecore.Configuration;
using Sitecore.Data;
using Sitecore.Data.Items;
using Sitecore.Publishing;
using Sitecore.Workflows.Simple;
// set publish options
PublishOptions myOptions = new PublishOptions(PublishMode.Smart, Sitecore.Data.Managers.LanguageManager.DefaultLanguage, DateTime.Now);
Database sourceDatabase = Sitecore.Configuration.Factory.GetDatabase( “master” );
myOptions.RootItem = sourceDatabase.Items[ “/sitecore/content” ];
// get the publish target. Iterate through the /sitecore/system/publishing targets children.
string target = "web";
Database targetDatabase = Factory.GetDatabase(target);
// define the source and target databases
myOptions.SourceDatabase = sourceDatabase;
myOptions.TargetDatabase = targetDatabase;
// create a publisher
Publisher myPublisher = new Publisher( myOptions );
// publish in AsyncMode
Sitecore.Jobs.Job myPublishJob = myPublisher.PublishAsync( );
// publish in SyncMode
myPublishJob.Start();
// publish in SyncModemy