The key is to set the FolderServerRelativeUrl
of the CamlQuery
. Setting the Scope attribute to Recursive will return all items but not folders, setting it to RecursiveAll will bring back items plus folders.
Please try below code to get the documents from folder1
inside the DocLibrary
public static void GetListItemsInFolder()
{
ClientContext clientContext = new ClientContext("https://xxxxx.sharepoint.com/teams/site");
List list = clientContext.Web.Lists.GetByTitle("DocLibrary");
CamlQuery camlQuery = new CamlQuery();
camlQuery.ViewXml = @"<View Scope='Recursive'>
<Query>
</Query>
</View>";
camlQuery.FolderServerRelativeUrl = "/DocLibrary/folder1";
ListItemCollection listItems = list.GetItems(camlQuery);
clientContext.Load(listItems);
clientContext.ExecuteQuery();
ListItem itemOfInterest = listItems[0];
string creator = itemOfInterest.FieldValues["Created_x0020_By"].ToString();
string title = itemOfInterest.FieldValues["Title"].ToString();
}
UPDATED
You can use below function to get the files from a specific folder using CSOM
public List<file> ListFiles(string libraryName, string folderName)
{
using (ClientContext clientContext = new ClientContext("your site url")
{
List<portalfile> fileList = new List<portalfile>();
var domain = "domain";
var username = "username";
var password = "password";
clientContext.Credentials = new NetworkCredential(username, password, domain);
Web web = clientContext.Web;
ListCollection lists = web.Lists;
var docLib = web.Lists.GetByTitle(libraryName);
clientContext.Load(docLib,
d => d.Title,
d => d.RootFolder.Name);
clientContext.ExecuteQuery();
String folderUrl = String.Format("/{0}/{1}", docLib.RootFolder.Name, folderName);
var folders = docLib.RootFolder.Folders;
clientContext.Load(folders, fldrs => fldrs.Include(fldr => fldr.ServerRelativeUrl));
clientContext.ExecuteQuery();
var folder = folders.FirstOrDefault(f => f.ServerRelativeUrl.ToLower() == folderUrl.ToLower());
if (folder != null)
{
var files = folder.Files;
clientContext.Load(files, fls => fls.Include(fl=> fl.Name));
clientContext.ExecuteQuery();
}
return files.ToList();
}
}