I write a lot of code using the SharePoint object model. Often times, I want to check to see if a particular Web exists in a Site Collection or a List exists in a Web. I used to write methods that enumerated through the collection to see if they existed or I wrapped a Try-Catch block around the code in case the object didn’t exist.
Recently I came across a code snippet that made checking for the existence of a web or list easy. I can’t remember where I found it so I’ll thank the nameless person who originally wrote the code. I’m only capturing it here for my own reference and possibly help someone else.
static bool ListExists(SPWeb web, string listName)
{
return web.Lists.Cast().Any(list => string.Equals(list.Title, listName));
}
static bool WebExists(SPSite site, string webName)
{
return site.AllWebs.Cast().Any(web => string.Equals(web.Name, webName));
}
6 responses to “Easy Check If An SPWeb/SPList Exist”
We can check if webName is existing SPWebCollection.Names.
So i often use a extension method for SPWebCollection:
public static class SPWebCollectionExtension
{
public static Boolean Contains(this SPWebCollection webCollection, String webName)
{
if (webCollection == null) throw new ArgumentNullException(“webCollection”);
if (String.IsNullOrEmpty(webName)) throw new ArgumentException(“webName”);
return Array.Exists(webCollection.Names, s => s.Equals(webName, StringComparison.CurrentCultureIgnoreCase));
}
}
Nice blog! Thanks for sharing!
Thanks a lot
These methods are not very efficient if there are a large number of lists/webs, because all of them are iterated.
To check if a list exists, better use the TryGetList() approach:
return web.Lists.TryGetList(listName) != null
Thank you everyone for commenting on this post. I want to clarify a few things:
Keep the comments coming. I learn something new everyday!
[…] great post, one of those finer details of SharePoint API development that I use a lot as well: Easy Check If An SPWeb/SPList Exist By David Petersen, January 20, 2010 2:57 […]