Get the URL of a list

This is a seemingly simple task – given a List or Library in SharePoint, how do I get it’s URL? The difficulty here is that a List has multiple URLs – one for each View on the list. We can get those URLs, but sometimes you really just want the URL to the list, without the /forms/something.aspx bit too.

For example, you might want http://server/siteCollection/site/lists/somelist . If you entered this URL, you’d be taken to the default View for the list, so you don’t really need the extra /forms/… bit to identify the list – that’s all about identifying the view.

Sadly, though, there is no SPList.Url property or equivalent on the SPList object. So, how can I get a list’s URL? Well, all Lists have a RootFolder. This folder has a URL, relative to the SPWeb it’s in, or a ServerRelativeUrl, relative to the server root.

So, we can do something like this:

string url = list.RootFolder.ServerRelativeUrl

Well, that’s great – but what about the absolute URL, including the server name? This can differ in SharePoint with alternate access mappings, and so can be slightly more complicated:

string url = "http://server/subsite/Documents/";

using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.GetList(url);
        string absoluteListUrl = site.MakeFullUrl( list.RootFolder.ServerRelativeUrl );
Console.WriteLine(absoluteListUrl );
}
}
Advertisements
Get the URL of a list

4 thoughts on “Get the URL of a list

  1. Erich Stehr says:

    With the core as a one-liner:
    public static ListServerRelativeUrl(SPList list)
    {
    return String.Concat(list.Web.ServerRelativeUrl.TrimEnd('/'), "/", list.RootFolder.Url);
    }

    Agreed with above, brilliant!

    Like

    1. You mean SPSite.MakeFullUrl() – yes, quite right. I’ve updated the examples above to show using that, which is a much better way.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s