Get sitecore item relative path by item id/path

- Pranay on Apr 15 '16

Sometimes you might need to get the relative path of a Sitecore item, say there is an item 'Sitecore/Content/Home/Categories/Products/MyProduct' which represents a page in your website with URL 'http://yoursitename/Categories/Products/MyProduct', now if you want to get the relative path i.e., '/Categories/Products/MyProduct', then this post might be for you..

Code to get item relative path/URL

Below is the simple I have used to do the same. First get the Sitecore item path and then remove the root path and start item name from that path to get the relative path.

public static string GetItemRelativeURL(Item item)
    string itemPath = item.Paths.Path.ToString().ToLower();
    itemPath = itemPath.Replace(Sitecore.Context.Data.Site.RootPath.ToLower(), "");
    itemPath = itemPath.Replace(Sitecore.Context.Data.Site.StartItem.ToLower(), "");
    return itemPath;

Hope it helps you. Please comment if you have any suggestions.

About the author

Pranay Deegoju
Sitecore Certified Professional

A Software Engineer by profession, a part time blogger and an enthusiast programmer. You can find more about me here.

Leave your comments on this post here