Programmatically Check whether a Particular List/Library Exists or Not

How to check if a list exists in SharePoint programmatically?

SharePoint 2010 offers TryGetList Method to determine the existence of a List programmatically. TryGetList returns null if the specified list doesn’t exist.

SharePoint 2010 check if list exists:

using (SPSite site = new SPSite("http://sharepoint.company.com/sites/sales/"))
{
	using (SPWeb web = site.RootWeb)
	{
		    SPList ProjectList = Web.Lists.TryGetList("Project Documents");
		    if (ProjectList != null)
			{
				ProjectList.Delete();
			}
	}
}

MOSS 2007: In SharePoint 2007, we have to write our own method to check if a particular list exists or not.

SharePoint 2007 check if list exists in C#:

//Method to Get whether the particular list exists or Not
public static bool ListExists(SPWeb web, string listName)
{
	var lists = web.Lists;
	foreach (SPList list in lists)
	{
		if (list.Title.Equals(listName))
			return true;
	}
	return false;
}

Before Deleting/creating a List, we can call the above function as:

using (SPSite site = new SPSite("http://sharepoint.company.com/sites/sales/"))
{
	using (SPWeb web = site.RootWeb)
	{
		if (ListExists(web, "Project Documents"))
		{
			web.Lists["Project Documents"].Delete();
		}
	}
}

Salaudeen Rajack

Information Technology Professional with Two decades of SharePoint Experience.

2 thoughts on “Programmatically Check whether a Particular List/Library Exists or Not

  • March 5, 2013 at 3:01 PM

    In 2007, instead of looping through, can I just use:

    SPList listObj = null;
    try {
       listObj = web.Lists[listName];
    }
    catch (ArgumentException) {
       // do something
    }
    finally {
       return listObj != null;
    }

    Reply
    • March 6, 2013 at 7:32 AM

      Sure it works, Ashwin. But I’m not happy with the try/catch statement as it is expensive throwing an exception when a list doesn’t exist! If you still want to use this method, The complete code would be:

      //Method to Check List Exists
      public static Boolean checkListExists(string listName, SPWeb oSPWeb)
      {
      try
      {
      SPList oSPList = oSPWeb.Lists[listName];
      return true;
      }
      catch (ArgumentException)
      {
      return false;
      }
      }

      I’ve used the similar Try/Catch method to check if site exists in one of my automation code: Automating Site Delete Process in SharePoint

      Reply

Leave a Reply