Checking if a SPFolder Exists
Posted by mundeep on February 24, 2009
Ran into a colleague’s code that was incorrectly trying to check if a folder existed. It was something like:
private bool CheckFolderExists(SPWeb parentWeb, string folderName) {
SPFolder folder = parentWeb.GetFolder(folderName);
if (folder == null) {
return false;
}
else {
return true;
}
}
however this always returns an actual SPFolder object, and the correct way is to check the Exists property of the returned object ie:
private bool CheckFolderExists(SPWeb parentWeb, string folderName) {
SPFolder folder = parentWeb.GetFolder(folderName);
return folder.Exists;
}
NB: Yes, this post is almost identical to my earlier one about checking if an SPWeb object exists.
Ulrich said
If it worked as easy as this we would all be very happy puppies. In reality, SPFolder.Exists does return true if the folder exists but throws an exception if it doesn’t. Poor coding practice? Depends on how you look at it: As a non-admin, you are probably not supposed to successfully guess at the existence or non-existence of objects. Some MS developer might have thought about this and came up with this solution. Which is not helpful, of course.
Zick said
Hello,
thanks for the tip, it will be usefull for me