Share via


Get parent folder using client object model

Question

Thursday, June 26, 2014 3:36 PM

In my program, I have information about list item:

List list1 = ctx.Web.Lists.GetByTitle("testLib");
ListItem listItem = list1.GetItemById(3);                 
ctx.Load(list1);
ctx.Load(listItem, w => w.DisplayName, w => w.FileSystemObjectType);
ctx.ExecuteQuery();

I need to know does this list item belong to a folder, i.e. I need to know name of his parent folder (or maybe it doesn't have a parent folder). How can I do that??

All replies (2)

Friday, June 27, 2014 10:46 AM âś…Answered | 1 vote

private static Folder GetListItemFolder(ListItem listItem)
{
    var folderUrl = (string)listItem["FileDirRef"];
    var parentFolder = listItem.ParentList.ParentWeb.GetFolderByServerRelativeUrl(folderUrl);
    listItem.Context.Load(parentFolder);
    listItem.Context.ExecuteQuery();
    return parentFolder;
}
using (var context = new ClientContext(webUrl))
{
      var list = context.Web.Lists.GetByTitle(listTitle);
      var items = list.GetItems(CamlQuery.CreateAllItemsQuery());
      context.Load(items);
      context.ExecuteQuery();


      foreach (var item in items)
      {
         var folder = GetListItemFolder(item); //get Folder
         Console.WriteLine(folder.Name);
      }
}

check this

http://sharepoint.stackexchange.com/questions/93052/is-there-a-way-to-get-folder-object-from-listitem-one


Friday, June 27, 2014 9:16 AM

Hi,

According to your post, my understanding is that you wanted to get the parent folder using client object model.

The following code snippets for your reference.

var query = new CamlQuery

                {

                    ViewXml = string.Format("<View Scope=\"RecursiveAll\"><Query><Where><And><Eq><FieldRef Name=\"FSObjType\" /><Value

Type=\"Integer\">1</Value></Eq><Eq><FieldRef Name=\"FileRef\" /><Value Type=\"Text\">{0}</Value></Eq></And></Where></Query></View>", folder.ServerRelativeUrl)

                };

var list = cc.Web.Lists.GetByTitle("ListTitle"); // You should know list title where your folder located

cc.Load(list);

var items = list.GetItems(query);

cc.Load(items);

cc.ExecuteQuery();

var folderListItem = items.Count > 0

                            ? items[0]

                            : null;

Console.WriteLine("Name: " + folder.Name);

if (folderListItem != null)

    Console.WriteLine("City: " + folderListItem.FieldValues["City"]);

http://social.msdn.microsoft.com/Forums/en-US/57af69f8-c4b0-4fb7-acd1-5b4f0179e760/fetch-parent-folder-data-using-sharepoint-client-object-model?forum=sharepointdevelopmentprevious

Thanks & Regards,

Jason

Jason Guo
TechNet Community Support