Is there a way to get Folder object from ListItem one?

僤鯓⒐⒋嵵緔 提交于 2019-12-05 21:50:59

It actually depends on which version of SharePoint is used.

SharePoint 2013

In SharePoint 2013 CSOM ListItem.Folder property gets a folder object that is associated with a folder item.

SharePoint 2010

In SharePoint 2010 CSOM Folder property is not exposed for ListItem object.

The following method could be used for retrieving Folder associated with ListItem:

/// <summary>
/// Get Parent Folder for List Item
/// </summary>
/// <param name="listItem"></param>
/// <returns></returns>
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;
}

Example:

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);
      }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!