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 ); } }
I’ve been hunting for the answer to this problem all morning! Brilliant, thanks! 🙂
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!
u can use sputility.makefullurl();
You mean SPSite.MakeFullUrl() – yes, quite right. I’ve updated the examples above to show using that, which is a much better way.