Today I searched for a quick code sample to create a nested folder structure inside a SharePoint library with CSOM.
Unfortunately I could not find one so created one myself. I’m sure the code can be optimised but it does the trick …
/// <summary> /// Will ensure nested folder creation if folders in folderPath don't exist. /// </summary> /// <param name="ctx">Loaded SharePoint Client Context</param> /// <param name="list">Document Library SharePoint List Object</param> /// <param name="folderPath">List of strings ParentFolder, ChildFolder, ...</param> /// <returns>Last ChildFolder as target</returns> private static Folder EnsureAndGetTargetFolder(ClientContext ctx, List list, List<string> folderPath) { Folder returnFolder = list.RootFolder; if (folderPath != null && folderPath.Count > 0) { Web web = ctx.Web; Folder currentFolder = list.RootFolder; ctx.Load(web, t => t.Url); ctx.Load(currentFolder); ctx.ExecuteQuery(); foreach (string folderPointer in folderPath) { FolderCollection folders = currentFolder.Folders; ctx.Load(folders); ctx.ExecuteQuery(); bool folderFound = false; foreach (Folder existingFolder in folders) { if (existingFolder.Name.Equals(folderPointer, StringComparison.InvariantCultureIgnoreCase)) { folderFound = true; currentFolder = existingFolder; break; } } if (!folderFound) { ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation(); itemCreationInfo.UnderlyingObjectType = FileSystemObjectType.Folder; itemCreationInfo.LeafName = folderPointer; itemCreationInfo.FolderUrl = currentFolder.ServerRelativeUrl; ListItem folderItemCreated = list.AddItem(itemCreationInfo); folderItemCreated.Update(); ctx.Load(folderItemCreated, f => f.Folder); ctx.ExecuteQuery(); currentFolder = folderItemCreated.Folder; } } returnFolder = currentFolder; } return returnFolder; }
If you want to create nested subfolders this appears to work to create /A/B/C. And each “folder” name needs to be 128 characters or less.
var folder1 = list.RootFolder.Folders.Add(“A”);
var folder2 = folder1.Folders.Add(“B”);
var folder3 = folder2.Folders.Add(“C”);
ctx.ExecuteQuery();