0

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

Code:

public string GetAllFiles()
    {
        var returnResult = "<ul>";
        var items = new List<ListItem>();
        try
        {
            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();
                    recordsList.Add(rec);

                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);
        ctx.Load(folderItems);
        ctx.ExecuteQuery();
        var allFolders = folderItems.ToList();
        return allFolders;
    }
0

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, privacy policy and cookie policy

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