I'm trying to get Folder object by its path in SharePoint 2010 client application using Client Side Object Model (.Net 4.0).
I need to check whether folder described by 'folderPath' variable exists in the library and then get the Folder object for further operations. To enhance performance, I chose to use CAML query to filter the list.
My code:
IEnumerable<List> library = this.clientContext.LoadQuery(
this.clientContext.Web.Lists.Where(p => p.Title == this.documentLibrary));
this.clientContext.ExecuteQuery();
List libraryList = library.FirstOrDefault();
//code to handle libraryList == null
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml =
"<View Scope=\"RecursiveAll\">" +
"<Query>" +
"<Where>" +
"<And>" +
"<Eq>" +
"<FieldRef Name=\"FSObjType\"/>" +
"<Value Type=\"Integer\">1</Value>" +
"</Eq>" +
"<Eq>" +
"<FieldRef Name=\"FileRef\" />" +
"<Value Type=\"Text\">" + folderPath + "</Value>" +
"</Eq>" +
"</And>" +
"</Where>" +
"</Query>" +
"</View>";
ListItemCollection items = libraryList.GetItems(camlQuery);
clientContext.Load(items);
clientContext.ExecuteQuery();
To this point everything is OK. But I don't have any idea how get the 'Folder' object from an item. I tried to do it in this way:
Folder folder = items.FirtsOrDefault().Folder;
clientContext.Load(folder);
clientContext.ExecuteQuery();
and that way (used instead of last three lines from first code snippet):
ListItemCollection items = libraryList.GetItems(camlQuery);
clientContext.Load(items, collection => collection.Include(item => item.Folder));
clientContext.ExecuteQuery();
But in both cases I got an Exception:
1st: 'Field or property 'Folder' does not exist.'
2nd: 'Column 'Folder' does not exist. It may have been deleted by another user.'
Is there a way to do it? Or maybe I'm doing something wrong? Thanks in advance for the help.
It actually depends on which version of SharePoint is used.
In SharePoint 2013 CSOM ListItem.Folder property gets a folder object that is associated with a folder item.
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);
}
}