How to get the Managed Path for a Site Collection

There’s no easy way of retrieving the Managed Path for a Site Collection (SPSite) through the SharePoint 2010 object model.

Therefore, I wrote this method, to retrieve it for you. It should work with both wildcard inclusion and explicit inclusion Managed Paths, including nested managed paths (i.e. /sites/, /sites/projects/, /sites/depts/, etc.).

private Microsoft.SharePoint.Administration.SPPrefix GetManagedPath(SPSite site)
{
    if (site == null)
        throw new ArgumentNullException("site");
    string relativeUrl = site.ServerRelativeUrl;
    if (relativeUrl.Length == 0)
        throw new Exception("Invalid ServerRelativeUrl for this SPSite.");

    foreach (Microsoft.SharePoint.Administration.SPPrefix prefix in site.WebApplication.Prefixes)
    {
        switch (prefix.PrefixType)
        {
            case Microsoft.SharePoint.Administration.SPPrefixType.ExplicitInclusion:
                if (relativeUrl == "/" + prefix.Name || relativeURL == prefix.Name)
                    return prefix;
                break;
            case Microsoft.SharePoint.Administration.SPPrefixType.WildcardInclusion:
                // WildCard Inclusion prefixes can be nested (i.e. /sites/ , /sites/projects/, /sites/depts/).
                // Thus, we remove the site collection's name and compare against the whole string, in stead of using .StartsWith()
                if (relativeUrl.Substring(0, relativeUrl.LastIndexOf("/")) == "/" + prefix.Name)
                    return prefix;
                break;
        }
    }
    // A prefix should've been returned by now.
    throw new Exception("No SPPrefix (Managed Path) found for this SPSite");
}

The method returns an SPPrefix class, which contains the Name and PrefixType properties of the Managed Path. If the Site Collection is located at the root of the Web Application, the SPPrefix.Name property will be empty and of the type Explicit Inclusion.

One thought on “How to get the Managed Path for a Site Collection

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>