Access the ancestors of an item

Version:

You can use the Sitecore.Data.Items.Item.Parent property in a recursive method to access the ancestors of an item. For example, to access the ancestors of the /Sitecore/Content/Home item in the Master database:

Sitecore.Data.Database master = Sitecore.Configuration.Factory.GetDatabase("master");

Sitecore.Data.Items.Item home = master.GetItem("/sitecore/content/home");

ProcessRecursively(home.Parent);

...

private void ProcessRecursively(Sitecore.Data.Items.Item item)
{
    if (item.Parent != null )
    {
        // Process parent item
        ProcessRecursively(item.Parent);
    }
}
Warning

If the recursive method passes its argument to itself, then that method enters an infinite loop.

If you have suggestions for improving this article, let us know!