Programmatically Check whether a Particular List/Library Exists or Not
How to check if 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:
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#:
Before Deleting/creating a List, we can call the above function as:
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(); } } }
In 2007, instead of looping through, can I just use:
ReplyDeleteSPList listObj = null;
try {
listObj = web.Lists[listName];
}
catch (ArgumentException) {
// do something
}
finally {
return listObj != null;
}
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:
Delete//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