OK so your requirement is to recursively check each parent item to find the deepest 'unpublished' parent, then publish.
You can do this by simply trying to grab the item from the web database. If the item is not null then it exists.
You could try something like below (note I have tested this):
var master = Sitecore.Configuration.Factory.GetDatabase("master");
var yourItem = master.GetItem("/sitecore/content/path/to/item");
var itemToPublish = FindUnpublishedItem(yourItem);
if(IsPubishable(itemToPublish))
{
SmartPublishToTarget(itemToPublish, master, true);
}
public Item FindUnpublishedItem(Item item)
{
var web = Sitecore.Configuration.Factory.GetDatabase("web");
var parentInWeb = web.GetItem(item.ParentID);
if (parentInWeb == null) return FindUnpublishedItem(item.Parent);
return item;
}
private void SmartPublishToTarget(Item item, Database master, bool publishDescendants)
{
var publishToTargetUser = @"sitecore\PublishToTargetUser";
if (Sitecore.Security.Accounts.User.Exists(publishToTargetUser))
{
var scUser = Sitecore.Security.Accounts.User.FromName(publishToTargetUser, true);
using (new Sitecore.Security.Accounts.UserSwitcher(scUser))
{
var targetDb = Sitecore.Configuration.Factory.GetDatabase("web");
var publishOptions = new Sitecore.Publishing.PublishOptions(master,
targetDb,
Sitecore.Publishing.PublishMode.Smart,
item.Language,
DateTime.Now);
var publisher = new Sitecore.Publishing.Publisher(publishOptions);
publisher.Options.RootItem = item;
publisher.Options.Deep = publishDescendants;
publisher.Publish();
}
}
else
{
throw new UnauthorizedAccessException("publishToTargetUser does not appear to be setup in sitecore");
}
}
private bool IsPubishable(Item item)
{
return item.Publishing.IsPublishable(DateTime.Now, false);
}
Note: I believe it is better practice to use UserSwitcher() rather than SecurityDisabler(). This allows you to lock down only the required actions needed for this task. In order for it to work though, you will need tocreate the user in sitecore and assign permissions to access and publish the specific area in content tree.