SharePoint Microsoft.SharePoint.Client.CamlQuery recursively return folders only (including subfolders) - sharepoint

I am attempting to pull back all the Folders and SubFolders (there can be any number) from a SharePoint site. I don't want the files (there could be thousands), so I am basically trying to just build a folder hierarchy. Additionally I only want the User created folders and the main "Documents" folders, not all the system ones.
That said, I found the following example that I though should have worked, but when I reduce it to just the folders I only get the top level folders:
https://stackoverflow.com/questions/16652288/sharepoint-client-get-all-folders-recursively
Here is the state of the current code. I am probably just missing something on the load (like an expresssion?):
public static void LoadContent(Microsoft.SharePoint.Client.Web web, out Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.Folder>> listsFolders)
{
listsFolders = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.Folder>>();
var listsItems = new Dictionary<string, IEnumerable<Microsoft.SharePoint.Client.ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Where(l => l.BaseType == Microsoft.SharePoint.Client.BaseType.DocumentLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
var items = list.GetItems(Microsoft.SharePoint.Client.CamlQuery.CreateAllFoldersQuery());
ctx.Load(items);
listsItems[list.Title] = items;
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == Microsoft.SharePoint.Client.FileSystemObjectType.Folder).Select(i => i.Folder);
}
}
UPDATE
Just to help out anyone else who might just want the main folders and subfolders as a list of urls, here is the final code. I suspect it could be simplified but it is working. The trick after the help below was to get the "root" folder paths, which required a separate query. I think that is where it could prove easier to just get Folders -> Subfolders, but I have Folders -> Subfolders -> Subfolders and this solution gets that last subfolder, along with the root folders.
public static void LoadContent(Microsoft.SharePoint.Client.Web web, List<String> foldersList)
{
Dictionary<string, IEnumerable<Folder>> listsFolders = new Dictionary<string, IEnumerable<Folder>>();
var listsItems = new Dictionary<string, IEnumerable<ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Include(l => l.Title).Where(l => l.BaseType == BaseType.DocumentLibrary && !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
ctx.Load(list.RootFolder);
ctx.ExecuteQuery();
}
foreach (var list in lists)
{
if (list.Title != "Form Templates" && list.Title != "MicroFeed" && list.Title != "Site Assets" && list.Title != "Site Pages")
{
foldersList.Add(list.RootFolder.ServerRelativeUrl);
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
listsItems[list.Title] = items;
}
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == FileSystemObjectType.Folder).Select(i => i.Folder);
}
foreach (var item in listsFolders)
{
IEnumerable<Folder> folders = item.Value;
foreach (Folder folder in folders)
{
foldersList.Add(folder.ServerRelativeUrl);
}
}
}
An example of what this returns:

1) In the provided example, to return Folder object, it needs to be explicitly included otherwise the exception occur, so replace the line:
ctx.Load(items);
with:
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
2) "system" libraries could be excluded like this:
var lists = ctx.LoadQuery(web.Lists.Where(l => !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
Modified example
public static void LoadContent(Web web, out Dictionary<string, IEnumerable<Folder>> listsFolders)
{
listsFolders = new Dictionary<string, IEnumerable<Folder>>();
var listsItems = new Dictionary<string, IEnumerable<ListItem>>();
var ctx = web.Context;
var lists = ctx.LoadQuery(web.Lists.Include(l =>l.Title).Where(l => l.BaseType == BaseType.DocumentLibrary && !l.Hidden && !l.IsCatalog && !l.IsSiteAssetsLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
var items = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.Folder));
listsItems[list.Title] = items;
}
ctx.ExecuteQuery();
foreach (var listItems in listsItems)
{
listsFolders[listItems.Key] = listItems.Value.Where(i => i.FileSystemObjectType == FileSystemObjectType.Folder).Select(i => i.Folder);
}
}

Try this.
var lists = ctx.LoadQuery(ctx.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
Console.WriteLine(list.Title);
ListItemCollection listitems = list.GetItems(CamlQuery.CreateAllFoldersQuery());
ctx.Load(listitems, items => items.Include(item => item.Id,item=>item.Folder));
ctx.ExecuteQuery();
foreach (var item in listitems)
{
Console.WriteLine(item.Folder.ServerRelativeUrl);
}
}

Related

Fields except Id and Tile are NULL

I'm facing a problem, all fields except ID, Title, Created, etc.. are Null, so all custom columns won't load any value.
I Tried to load the ListItems with Include, but result is still the same.
What am I doing wrong?
var participants = Spo.GetParticipants(true);
var oList = Ctx.Web.Lists.GetByTitle("Participant");
var camlQuery = new CamlQuery
{
ViewXml = "<ViewScope='RecursiveAll'><RowLimit>5000</RowLimit></View>"
};
var listItems = oList.GetItems(camlQuery);
//Ctx.Load(listItems,
// items => items.Include(
// item => item["ID"],
// item => item["Title"],
// item => item["Email"],
// item => item["FirstName"],
// item => item["Company"],
// item => item["Phone"],
// item => item["Street"],
// item => item["ZipCode"],
// item => item["City"]), items => items.ListItemCollectionPosition);
Ctx.Load(oList);
Ctx.Load(listItems);
Ctx.ExecuteQuery();
foreach (var oListItem in listItems)
{
foreach (var it in participants)
{
if (oListItem != null && oListItem["Email"].ToString() == it.Email)
{
oListItem["FirstName"] = it.FirstName;
oListItem["LastName"] = it.LastName;
oListItem["Company"] = it.Company;
oListItem["Phone"] = it.Phone;
oListItem["Street"] = it.Street;
oListItem["ZipCode"] = it.ZipCode;
oListItem["City"] = GetLookupCity(it.City);
//FieldLookupValue lv = new FieldLookupValue();
//lv.LookupId = int.Parse() it.City
p = "UPDATED: " + it.Email;
}
else
{
}
}
}
There should be something wrong with camlquery. There should be blank between View and Scope
<View Scope='RecursiveAll'><RowLimit>5000</RowLimit></View>

How to change the content type of list items

Im trying to change the content type of all my Root Folders in a document library. I am not even sure if that is possible. When i run the code below i get the message that ListItem.ContentType is Writeprotected...
My Question is, is it possible to change the content type at all?
If yes how do i do it with CSOM?
Thanks
ContentType ct = list.ContentTypes.GetById("0x0120D520008AE499F0AEB1C647B9D6F0C9D3B7F9F100B56E2AEF9C715540BE5E87A04F54476E");
context.ExecuteQuery();
foreach (ListItem item in items)
{
context.Load(item, i => i.DisplayName);
context.Load(item, i => i.ContentType);
context.Load(ct, i => i.Id);
context.ExecuteQuery();
if (item.ContentType.Name == "Folder")
{
Console.WriteLine("Name: " + item.DisplayName + " ContentType:" + item.ContentType.Name);
if (item.ContentType.Sealed = true)
{
item.ContentType.Sealed = false;
item.Update();
context.ExecuteQuery();
}
item.ContentType = ct.Id;
item.Update();
context.ExecuteQuery();
}
}
Update the item content type like this, setting ContentTypeId field value:
List list = ctx.Web.Lists.GetByTitle("doc2");
ContentType ct = list.ContentTypes.GetById("0x0120001D61DFC51D574148B41D5DEB19779D19000C2B25DED7B1C34BB491C5BE59765450");
ctx.Load(ct);
ctx.ExecuteQuery();
CamlQuery caml = new CamlQuery();
ListItemCollection items = list.GetItems(caml);
ctx.Load(items);
ctx.ExecuteQuery();
foreach (ListItem item in items)
{
ctx.Load(item, i => i.DisplayName);
ctx.Load(item, i => i.ContentType);
ctx.Load(ct, i => i.Id);
ctx.ExecuteQuery();
if (item.ContentType.Name == "Folder")
{
item["ContentTypeId"] = ct.Id.ToString();
item.Update();
ctx.ExecuteQuery();
}
}

Update/Change custom TaxonomyFieldValue in document library list in sharepoint using C# CSOM

list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}

List all external users SharePoint Online

Is there a way other than powershell (CSOM or JSOM) to list all external users?
I want to list all external users and "their permissions".
I ended upp doing a console application that exports all external users and their permissions on all sites, lists, files and folders in a sitecollection.
It was done quickly, so code modification could most certainly be done to fit your requirements better.
This solution exports a .csv file with the content.
Just copy paste from the "Program.class"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Security;
using Microsoft.SharePoint.Client;
using System.Net;
namespace ListExternalUsersCSOM
{
class Program
{
// Output to filesystem
private static string filePath = #"C:\Users\User\Desktop\output.csv";
// Builds the content to export to the csv file
private static StringBuilder csv = new StringBuilder();
// Groupcollection of all sitegrups and their members
// Only want one trip to the server for this
private static GroupCollection groups;
static void Main(string[] args)
{
// Sitecollection url, username and password of admin account
var webUri = new Uri("https://tenant.sharepoint.com/sites/intranet");
const string userName = "admin#tenant.com";
const string password = "Password";
var securePassword = new SecureString();
foreach (var c in password)
{
securePassword.AppendChar(c);
}
// Create credentials and context
var credentials = new SharePointOnlineCredentials(userName, securePassword);
var ctx = new Microsoft.SharePoint.Client.ClientContext(webUri);
ctx.Credentials = credentials;
// Get rootweb and the groups for the sitecollection
var rootWeb = ctx.Web;
groups = rootWeb.SiteGroups;
// Load groupcollection and load certain properties in every group right away
ctx.Load(groups, groups => groups.Include(g => g.Title, g => g.Users, g => g.Id));
// Load rootweb, subsites, lists, relative url, title, uniqueroleassingments
// Inlcude uniqueroleassingments and title in lists, spares us a trip to the server
ctx.Load(rootWeb, w => w.Webs, w => w.ServerRelativeUrl, w => w.Title, w => w.Lists.Include(l => l.HasUniqueRoleAssignments, l => l.Title), w => w.HasUniqueRoleAssignments);
ctx.ExecuteQuery();
// First we do these checks for rootweb only, then we recursively check all subsites...
// If uniquepermissions on web, look for external users
if (rootWeb.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsWeb(rootWeb);
}
foreach (var list in rootWeb.Lists)
{
if (list.Title != "MicroFeed" | list.Title != "Delningslänkar")
{
ListHasUniqueRoleAssignment(rootWeb, list, ctx);
}
}
foreach (var subWeb in rootWeb.Webs)
{
WebHasUniqueRoleAssignmentRecursive(subWeb, ctx);
}
System.IO.File.WriteAllText(filePath, csv.ToString(), Encoding.UTF8);
}
private static void WebHasUniqueRoleAssignmentRecursive(Web spWeb, ClientContext ctx)
{
ctx.Load(spWeb, w => w.Webs, w => w.ServerRelativeUrl, w => w.Title, w => w.Lists.Include(l => l.HasUniqueRoleAssignments, l => l.Title), w => w.HasUniqueRoleAssignments);
ctx.ExecuteQuery();
if (spWeb.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsWeb(spWeb);
}
foreach (var list in spWeb.Lists)
{
if (list.Title != "MicroFeed" | list.Title != "Delningslänkar")
{
ListHasUniqueRoleAssignment(spWeb, list, ctx);
}
}
foreach (var subWeb in spWeb.Webs)
{
WebHasUniqueRoleAssignmentRecursive(subWeb, ctx);
}
}
private static void ListHasUniqueRoleAssignment(Web spWeb, List list, ClientContext ctx)
{
var listsFolders = new List<Folder>();
var listsFiles = new List<File>();
var listsItems = new List<ListItem>();
CamlQuery query = CamlQuery.CreateAllItemsQuery();
ListItemCollection items = list.GetItems(query);
ctx.Load(items, icol => icol.Include(i => i.FileSystemObjectType, i => i.HasUniqueRoleAssignments, i => i.File, i => i.Folder, i => i.File.ListItemAllFields.HasUniqueRoleAssignments, i => i.Folder.ListItemAllFields.HasUniqueRoleAssignments));
ctx.ExecuteQuery();
listsItems.AddRange(items);
if (list.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsList(spWeb, list);
}
foreach (var listItem in listsItems)
{
if (listItem.FileSystemObjectType == FileSystemObjectType.File && listItem.HasUniqueRoleAssignments)
{
listsFiles.Add(listItem.File);
}
else if (listItem.FileSystemObjectType == FileSystemObjectType.Folder && listItem.HasUniqueRoleAssignments)
{
listsFolders.Add(listItem.Folder);
}
}
foreach (File file in listsFiles)
{
if (file.ListItemAllFields.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsFile(spWeb, file);
}
}
foreach (Folder folder in listsFolders)
{
if (folder.ListItemAllFields.HasUniqueRoleAssignments)
{
getExternalUsersAndPermissionsFolder(spWeb, folder);
}
}
}
private static void getExternalUsersAndPermissionsWeb(Web spWeb)
{
var ctx = spWeb.Context;
var assignments = spWeb.RoleAssignments;
// Load roleassingment for web, include users and groups and their permissionslevels on this web
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
// Iterate trough all assingments
foreach (var roleAssingment in assignments)
{
// If a user loginname contains #ext# it is an external user, so print the user and the permission level
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Site \"{0}\": {1} har rättighet {2} ", spWeb.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
// If a group
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
// Go to groupcollection we got earlier, get the corresonding groups users
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
// Iterate trough users
foreach (var user in users)
{
// If a user loginname contains #ext# it is an external user, so print the user and the permission level
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Site \"{0}\": {1} har rättighet {2} ", spWeb.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsList(Web spWeb, List list)
{
var ctx = spWeb.Context;
var assignments = list.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Lista \"{0}\": {1} har rättighet {2} ", list.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Lista \"{0}\": {1} har rättighet {2} ", list.Title, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsFile(Web spWeb, File item)
{
var ctx = spWeb.Context;
var assignments = item.ListItemAllFields.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Fil \"{0}\": {1} har rättighet {2} ", item.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Fil \"{0}\": {1} har rättighet {2} ", item.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
private static void getExternalUsersAndPermissionsFolder(Web spWeb, Folder folder)
{
var ctx = spWeb.Context;
var assignments = folder.ListItemAllFields.RoleAssignments;
ctx.Load(assignments, assignment => assignment.Include(role => role.Member, role => role.RoleDefinitionBindings));
ctx.ExecuteQuery();
foreach (var roleAssingment in assignments)
{
if (roleAssingment.Member.LoginName.ToString().Contains("#ext") & roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.User))
{
var output = String.Format("Mapp\\Dokumentgrupp \"{0}\": {1} har rättighet {2} ", folder.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output);
csv.AppendLine(output);
}
else if (roleAssingment.Member.PrincipalType.Equals(Microsoft.SharePoint.Client.Utilities.PrincipalType.SharePointGroup))
{
var users = groups.Where(g => g.Title == roleAssingment.Member.Title).First().Users;
foreach (var user in users)
{
if (user.LoginName.ToString().Contains("#ext#"))
{
var output2 = String.Format("Mapp\\Dokumentgrupp \"{0}\": {1} har rättighet {2} ", folder.Name, roleAssingment.Member.Title, roleAssingment.RoleDefinitionBindings.First().Name);
Console.WriteLine(output2);
csv.AppendLine(output2);
}
}
}
}
}
}
}

Retrieve All Documents from all Subfolders in a Document Library - CSOM

I am using the client side object model approach C# in order to retrieve all list items from a document library containing sub folders. I checked out the MSDN documentation and I am stuck as to why I cannot get the field property, or if I am even doing this right.
NetworkCredential credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
ClientContext clientcontext = new ClientContext(Resources.defaultSPSite);
clientcontext.Credentials = credentials;
//Load Libraries from SharePoint
//Web site = clientcontext.Web;
clientcontext.Load(clientcontext.Web.Lists);
clientcontext.ExecuteQuery();
//List sharedDocumentsList = clientcontext.Web.Lists.GetByTitle("TestLDOCS");
//CamlQuery camlQuery = new CamlQuery();
//camlQuery.ViewXml = #"<View Scope='Recursive'><Query></Query></View>";
foreach (List list in clientcontext.Web.Lists)
{
clientcontext.Load(list);
clientcontext.ExecuteQuery();
//list.TemplateFeatureId.ToString().Equals("") &&
string baseType = list.BaseType.ToString();
string listTitle = list.Title.ToString();
if (list.BaseType.ToString().Equals("DocumentLibrary", StringComparison.InvariantCultureIgnoreCase) && list.Title.ToString().Equals("TestLDOCS", StringComparison.InvariantCultureIgnoreCase))
{
foreach (Folder subFolder in list.RootFolder.Folders)
{
foreach (File f in subFolder.Files)
{
Console.WriteLine((string) f.Title);
}
}
}
}
}
The error that I am receiving is that the "foreach(File f in subFolder.Files)" collection may not be initialized error. Is there anyway to get the field values of all documents in every subfolder within a document library using CSOM?
I know you can strongly type the field values as well with a list item ie (listItem["fieldName"]). Should I go this route instead?
Some recommendations:
1) Prefer ClientRuntimeContext.LoadQuery method to load a specific lists, for example:
var lists = ctx.LoadQuery(ctx.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
ctx.ExecuteQuery();
2) Since SharePoint SCOM supports Request Batching it is recommended to minimize the number of requests to the server. The following example demonstrates how to perform a single request to the server in order to load all files from document libraries:
foreach (var list in lists)
{
var items = list.GetItems(CreateAllFilesQuery());
ctx.Load(items, icol => icol.Include(i => i.File));
results[list.Title] = items.Select( i=>i.File);
}
ctx.ExecuteQuery();
3) Prefer to load all files via CAML query as demonstrated below:
public static CamlQuery CreateAllFilesQuery()
{
var qry = new CamlQuery();
qry.ViewXml ="<View Scope=\"RecursiveAll\"><Query><Where><Eq><FieldRef Name=\"FSObjType\" /><Value Type=\"Integer\">0</Value></Eq></Where></Query></View>";
return qry;
}
Then the following example will return all the files in library:
var items = list.GetItems(CreateAllFilesQuery());
ctx.Load(items, icol => icol.Include(i => i.File));
ctx.ExecuteQuery();
var files = items.Select( i=>i.File).ToList();
It is more optimized way of loading specific lists from performance perspective
Complete example
How to load all files from document libraries using SharePoint CSOM:
using (var ctx = new ClientContext(webUri))
{
var results = new Dictionary<string, IEnumerable<File>>();
var lists = ctx.LoadQuery(ctx.Web.Lists.Where(l => l.BaseType == BaseType.DocumentLibrary));
ctx.ExecuteQuery();
foreach (var list in lists)
{
var items = list.GetItems(CreateAllFilesQuery());
ctx.Load(items, icol => icol.Include(i => i.File));
results[list.Title] = items.Select( i=>i.File);
}
ctx.ExecuteQuery();
//Print results
foreach (var result in results)
{
Console.WriteLine("List: {0}",result.Key);
foreach (var file in result.Value)
{
Console.WriteLine("File: {0}", file.Name);
}
}
}
foreach (List list in clientcontext.Web.Lists)
{
clientcontext.Load(list);
clientcontext.ExecuteQuery();
//list.TemplateFeatureId.ToString().Equals("") &&
string baseType = list.BaseType.ToString();
string listTitle = list.Title.ToString();
if (list.BaseType.ToString().Equals("DocumentLibrary", StringComparison.InvariantCultureIgnoreCase) && list.Title.ToString().Equals("TestLDOCS", StringComparison.InvariantCultureIgnoreCase))
{
foreach (Folder subFolder in list.RootFolder.Folders)
{
clientcontext.Load(subFolder.Files);
clientcontext.ExecuteQuery();
foreach (File f in subFolder.Files)
{
Console.WriteLine((string) f.Title);
}
}
}
}
}

Resources