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("https://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("https://sharepoint.company.com/sites/sales/"))
{
	using (SPWeb web = site.RootWeb)
	{
		if (ListExists(web, "Project Documents"))
		{
			web.Lists["Project Documents"].Delete();
		}
	}
}

Salaudeen Rajack

Salaudeen Rajack - Information Technology Expert with Two decades of hands-on experience, specializing in SharePoint, PowerShell, Microsoft 365, and related products. Passionate about sharing the deep technical knowledge and experience to help others, through the real-world articles!

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

  • 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
    • 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

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