0

How can I check if a List exists on a website by URL of the List?

Example of the url: http://MyCompany.com/Lists/MyList

I would like to avoid the FileNotExists exception.

My current code:

SPList list = web.GetList(_SurveyListUrl); 
if (list != null)
{
    // some logic
}

Note!

I do not want to check the list by name

1

2 Answers 2

1

The url of a list is equivalent to the name of the lists rootfolder. So if you know the url, you can search through all lists using Linq. This is most likely not performance optimized, but it's what you're trying to.

SPList list = web.Lists.Cast<SPList>().FirstOrDefault(li => li.RootFolder.Name == listUrl);

if (list != null) {
    //code
}

This works for lists and document libraries aswell.

1

GetList will throw FileNotFoundException if URL is not found.

To avoid this you need to use TryGetList. But this require you to pass the List Title.

Best practice is to use TryGetList. Else you need to do something as below

SPList list = null;
try {
    list = web.GetList(listUrl);
} catch(FileNotFoundException e) {
    //list not exists - log error
}

if(list != null) {
    //code 
}

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.