Easy Check If An SPWeb/SPList Exist

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”

  1. 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));

  2. 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

  3. Thank you everyone for commenting on this post. I want to clarify a few things:

    1. These methods are only available if you reference System.Linq which is in .NET Framework 3.5. (Target framework: .NET Framework 3.5 from the Application, Project Properties).
    2. As long as you are targeting .NET Framework 3.5 in your project, you can use these methods on WSS 3.0 based projects.
    3. The way the lambda works is that is will iterate through the list until it finds a match or reaches the end. This is not the most efficient way but with WSS 3.0, it is the cleanest way (IMHO) outside of trapping an error in a TryCatch block.
    4. The TryGetList() method is only available in SharePoint 2010.

    Keep the comments coming. I learn something new everyday!

Leave a Reply

Your email address will not be published. Required fields are marked *