Getting ParentFolder from a custom list

Getting ParentFolder from a custom list header image

Getting items from a list is something most developers do a lot, and one of the nice functions you can use is the SPListItem.File.ParentFolder since it returns (what else could it do), the parent folder. Especially when you’re creating something with navigation like breadcrumbs or tabs, that function will provide you with enough information to display the desired info.

However this seems to have a little limitation, it only works on standard libraries that actually contains ‘items’ which means that if you are trying to use it on a custom list it won’t work. And most developers use custom lists / content types. I hit the same problem, but luckily someone posted a nice solution to this on MSDN (credits go to Donzola).

The following code will allow you to get the parent folder of a list item:

///<summary>
///Returns the parent folder of an item in a list.
///</summary>
///<param name="itemToFind">Item whose parent folder you are looking for.</param>
///<param name="folder">Folder object to look in.  Pass null to start from the root.</param>
///<returns>SPFolder object of parent folder or null if item isn't in a folder or if the item isn't found.</returns>

static SPFolder GetParentFolder(SPListItem itemToFind, SPFolder folder)
{
  SPQuery query = new SPQuery();
  query.Folder = folder;
  SPListItemCollection items = itemToFind.ParentList.GetItems(query);

  foreach (SPListItem item in items) {
    if (item.ID == itemToFind.ID) {
      return (folder);
    }

    if (item.Folder != null) {
      SPFolder resultFolder = GetParentFolder(itemToFind, item.Folder);
      if (resultFolder != null) {
        return (resultFolder);
      }
    }
  }

  return (null);
}

So adding that function allows you to get a parentfolder with: SPFolder parentFolder = GetParentFolder(item, null);

Final note; make sure that you check if the parentFolder != null before you use it.

Loading comments…