You can wonder why this is not build ind to the API from the start. But it is simple to extends the SPWeb class with an extra function. So you can be able to get a the SPList item by a relative url.
I have made the following code to return the SPList object from the relative url on the current site.
The following code is C#.
using System;
using Microsoft.SharePoint;
namespace BKNNet.Extenders
{
public static class SPWebExtension
{
/// <summary>
/// Gets the list by URL.
/// </summary>
/// <param name="rootweb">The rootweb.</param>
/// <param name="listUrl">The list URL.</param>
/// <returns></returns>
public static SPList GetListByUrl(this SPWeb rootweb, string listUrl)
{
SPSite site = rootweb.Site;
SPList list = null;
try
{
if (site != null)
{
// Strip the site url and use it to open web
string webUrl = listUrl.Substring(site.Url.Length);
// Strip off everything after /forms/
int formsPos = webUrl.IndexOf("/forms/", 0, StringComparison.InvariantCultureIgnoreCase);
if (formsPos >= 0)
{
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', formsPos));
}
// Strip off everything after /lists/
int listPos = webUrl.IndexOf("/lists/", 0, StringComparison.InvariantCultureIgnoreCase);
if (listPos >= 0)
{
// Must be a custom list, so remove anything after /lists/
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/', listPos));
}
else
{
// Not a list. Must be a document library, so we remove the document library name
webUrl = webUrl.Substring(0, webUrl.LastIndexOf('/'));
}
// Get the web site
using (SPWeb web = site.OpenWeb(webUrl))
{
if (web != null)
{
// Initialize to avoid COM exceptions
string title = web.Title;
// Get the list
list = web.GetList(listUrl);
}
}
}
}
catch
{
//Do error handling e.g. Logging
}
return list;
}
}
}