I need the following format when recursively retrieving folders, subfolders and files. Basically reproduce a "Windows Explorer" type of view with the data for the Website UI via C# and CSOM.

Any thoughts?

  • Folder 1
  • -> Subfolder 1
  • ->-> File 3
  • ->-> File 4
  • -> Subfolder 2
  • -> Subfolder 3
  • ->-> File 5
  • ->-> File 6
  • -> File 1
  • -> File 2

This is what I'm currently getting: Current results from code


public string GetAllFiles()
        var returnResult = "<ul>";
        var items = new List<ListItem>();
            using (var ctx = Auth())
                var documentLibrary = "TestDocuments";
                var list = ctx.Web.Lists.GetByTitle(documentLibrary);
                var folders = GetAllFolders(list);
                var recordsList = new List<FileModel>();
                foreach (var item in folders)
                    var rec = new FileModel();
                    rec.fileName = item["FileLeafRef"].ToString();
                    rec.filePath  = item["FileDirRef"].ToString();

                foreach (var item in recordsList.OrderBy(x => x.filePath))
                    returnResult += string.Format("<li>FileDirRef: {0}, FileLeafRef: {1}</li>", item.filePath, item.fileName);

            returnResult += "</ul>";

            return returnResult;

public class FileModel {
    public string fileName { get; set; }
    public string filePath { get; set; }

public static List<ListItem> GetAllFolders(List list)
        var ctx = list.Context;
        var qry = new CamlQuery();
        qry.ViewXml = "<View Scope='RecursiveAll'><Query><OrderBy><FieldRef Name=\"FileLeafRef\" Ascending=\"TRUE\"/></OrderBy></Query></View>";
        var folderItems = list.GetItems(qry);
        var allFolders = folderItems.ToList();
        return allFolders;

1 Answer 1


I would rewrite the code in a way that the orderby or sorting happens before or in the first loop, so as to get the root folders ordered initially and the second loop simply to output the root folder and the subfolders consecutively.

Alternatively, I would also suggest to map the SharePoint library as a network drive and use the command prompt to generate the report.

You could simply use the command - dir /s > c:FilesFolders.txt from the mapped drive and it would generate a similar hierarchical report with all the folders and files in the library. It is explained in detail here as option b.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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