2

I need to get the folder named Arshad from SharePoint Document library folder. The path of the sub folder is :

http://url/Shared Documents/Arshad

I need to access the folder using SharePoint Client object model.

When I try accessing, it shows me an error :

Couldn't find the path.

The following is my code:

    var list =  clientContext.Web.Lists.GetByTitle(MainFolderName)

If the variable `MainFolderName = "Shared Documents";` then I can access that folder and even add a new folder inside the "Shared Documents"

    var SPfolder = list.RootFolder;
    clientContext.Load(SPfolder);
    clientContext.ExecuteQuery();
    SPfolder = SPfolder.Folders.Add(FolderName);

Please help.

  • 1
    You are trying to get a folder, so why are you using a method designed to get a List? – Robert Lindgren Sep 15 '15 at 7:14
  • How to get a folder then.? I thought list is a way to get the folder..! – dahsra Sep 15 '15 at 7:17
  • 2
    A folder is a folder, a list is a list. See the first comment on this post for an example: andreaswijayablog.blogspot.se/2013/09/… – Robert Lindgren Sep 15 '15 at 7:18
  • 1
    tip: don't name your variables 'SP...' this creates confusing with the 'SharePoint Server Side object model' – Wout Sep 15 '15 at 9:11
5

Folders are items as well. Just get the item and load the folder property.

using (var ctx = new ClientContext(Constants.SharePointUri))
{    
   var list = ctx.Site.RootWeb.Lists.GetByTitle(Constants.Lists.Event.Name);
   var item = list.GetItemById(eventId);
   ctx.Load(list, d => d.Title, d => d.RootFolder.Name, d => d.Id);
   ctx.Load(item, d => d.DisplayName, d => d.Folder, d => d["FileRef"]);
   ctx.ExecuteQuery();

   // use item.Folder here
}

You can also use relative url's. A popular similar function is this one:

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;
}

To get folder by name you need the url containing the list and the name

using (var ctx = new ClientContext(Constants.SharePointUri))
{
   string folderName = "/MyList/aFolderName";  // watch out with spaces!!
   Web web = context.Web;
   List list = context.Web.Lists.GetByTitle("MyList");
   Folder folder = web.GetFolderByServerRelativeUrl(folderName);                

   ctx .Load(context.Web);
   ctx .Load(list);
   ctx .Load(folder);               
   ctx .ExecuteQuery();
}

To get items out of a folder use a CAML query.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.