SharePoint: Get the URL of a List or Library


Oddly enough, the SPList object doesn’t have a URL property which gives you the server relative URL of the List.

So, here’s a code snippet to retrieve it.

private static string GetListURL(SPList theList, bool serverRelative)
{
	var listUrl = theList.DefaultViewUrl;
	if (theList is SPDocumentLibrary)
	{
		var idx = listUrl.IndexOf("Forms");
		listUrl = listUrl.Remove(idx);
		if (listUrl.EndsWith("/"))
			listUrl = listUrl.Remove(listUrl.LastIndexOf("/"));
	}
	else
	{
		var idx = listUrl.LastIndexOf("/");
		listUrl = listUrl.Remove(idx);
	}
	if (!serverRelative)
	{
		var serverUrl = theList.ParentWeb.Url;
		serverUrl = serverUrl.Substring(0, serverUrl.IndexOf("/", 7));
		listUrl = serverUrl + listUrl;
	}

	return listUrl;
}

Published by

Phil Harding

SharePoint Consultant, Developer, Father, Husband and Climber.

2 thoughts on “SharePoint: Get the URL of a List or Library

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 )

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.