Thursday, September 2, 2010

Get the URL of a List in Sharepoint

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.
 So, we can do something like this:
string url = web.Url + "/" + list.RootFolder.Url
Well, that’s great – but the result has the full path, including the server name. This can differ in SharePoint with alternate access mappings, so it can be useful to get the server relative url instead. This 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 listurl = web.ServerRelativeUrl;
        if(listurl == "/") listurl = string.Empty;
        listurl = listurl + "/" + list.RootFolder.Url;
        Console.WriteLine(listurl);
    }
}
This should give use the server relative URL for the list. Note also the bit where we clear our variable if we are in the root site of the root site collection of a web application (e.g. http://server/ ) as this returns an SPWeb.ServerRelativeUrl of “/”