A few days ago I read a question on the SharePoint 2010 developer MSDN forum where part of the request was to check for the existence of a specific folder within a specific list. In the answer the check is simply done applying a try / catch block (try to get it and if it fails, create it).
One can read similar suggestions in this MSDN technical article as well:
“You should be prepared to catch exceptions when you write code that may fail if you ask for objects that may not exist.”
I agree that you should be prepared for this case but I’m pretty sure it should not be your default path. Exception handling should remain what its name suggests: handling exceptions, special cases. If there is other way to check object existence you should use that at first place, and not use exception handling to define program flow logic. The latter one may have serious performance issues and results typically quick-and-dirty “solutions”.
But how can we check whether an object exists or not? Let’s see a code sample for lists and folders:
In the above code we ask for the folder and list having the specified name and title. If the result is null the object does not exist.
If you call the GetFolderCS method using the exact list title and folder name of an existing list and folder, you get the folder object:
ClientContext clientContext = new ClientContext(http://sp2010);
Folder folder = GetFolderCS(clientContext, "Pages", "folder1");
If you test the solution further, you may found, that it is unfortunately case sensitive (that is the CS postfix in the method names). For example, if you type pages for a list named Pages, the result will be null, suggesting a non-existing list. That is due to the case sensitivity of the lambda expression used in the LoadQuery method of the ClientContext class.
Unfortunately, trivial methods to workaround this issue do not help, you will get ClientRequestException for the following trials:
list => list.Title.ToLower() == listTitle.ToLower()
The ‘ToLower’ member cannot be used in the expression.
list => list.Title.IndexOf(listTitle) == 0 && list.Title.Length == listTitle.Length
The ‘IndexOf’ member cannot be used in the expression.
list => list.Title.Equals(listTitle, StringComparison.CurrentCultureIgnoreCase))
The ‘Equals’ member cannot be used in the expression.
So what can we do to create a case insensitive version?
The solution is to get the list of the lists and the list of the folders within the list and compare its title and name locally as show in this slightly modified version:
In this case you can use the ToLower method that makes the result case insensitive.
I hope this version will help you to check for list and folder existence without misusing exception handling.