Wednesday, February 25, 2009

Get SPList.ID From URL

I often face a problem : I have an URL, and I would like to get the list pointed by this URL. So I wanted a function that could return me this ID whenever I was passing an URL to it!

Some Regexp, some recursivity and here we are :



public SPList getListFromUrl(string url)
{
try
{
if (!url.EndsWith("/")) url = url + "/";
//match list
Regex listExpReg = new Regex("(?.+)\\/Sites\\/(?.+)\\/Lists\\/(?.+)\\/.*", RegexOptions.IgnoreCase);
if (listExpReg.IsMatch(url))
{
Match siteMatch = listExpReg.Match(url);
String racine = siteMatch.Groups["Racine"].Value;
String siteToFind = siteMatch.Groups["Sites"].Value;
String listeToFind = siteMatch.Groups["LName"].Value;
String[] splitedSiteList = siteToFind.Split('/');
SPSite rootsite = new SPSite(racine + "/Sites/" + splitedSiteList[0]);
if (rootsite != null)
{
using (SPWeb webNavigated = rootsite.RootWeb)
{
foreach (string s in splitedSiteList)
{
if (s != splitedSiteList[0])
{
SPWeb TempWeb = webNavigated.Webs[s];
webNavigated = TempWeb;
TempWeb.Dispose();
}
}
SPList listsearched = webNavigated.GetList(url);
_destinationWeb = webNavigated;
rootsite.Dispose();
}
return listsearched;
}
else
{
return null;
}
}
else
return null;
}
catch (Exception exc)
{
//BUUUUUUUUP
}
}
The function basically return null if the URL passed is not a list URL, and return the list ID whenever you pass an URL to it. It also works when you pass the url containing some allitems.aspx after the name of the list...
Try it!
Hope it helps

No comments:

Post a Comment