In this article we will be seeing how to check if list exists using TryGetList method in SharePoint.
Normally we will be using SPList list = web.Lists[listName]; but it throws a null reference error if the list is not there. So we will be looping through the SPListItemCollection object and check if the list exists. In SharePoint 2010, a new method "TryGetList" is implemented to get the list and check if the list exists.
Using powershell script:
$siteURL="http://serverName:1111/"
$listName="Shared Documents"
$site=Get-SPSite $siteURL
$web=$site.RootWeb
$list=$web.Lists.TryGetList($listName)
if($list -ne $null)
{
write-host -f green $listName "exists in the site"
}
else
{
write-host -f yellow $listName "does not exist in the site"
}
📷
Using C# code:
using (SPSite site = new SPSite("http://serverName:1111/"))
{
using (SPWeb web = site.RootWeb)Â Â Â Â
{Â Â Â Â Â Â Â
SPList list = web.Lists.TryGetList("My List");
if (list != null)Â Â Â Â Â Â Â
 {        Â
Console.WriteLine("List exists in the site");Â Â Â Â Â Â Â Â
}
else       Â
{Â Â Â Â Â Â Â Â Â
Console.WriteLine("List does not exist in the site");Â Â Â Â Â Â Â Â
}Â Â Â Â Â Â Â Â Â
Console.ReadLine();Â Â Â Â Â
}
}
Kommentarer