Create a nested folder structure inside SharePoint with CSOM

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);
		foreach (string folderPointer in folderPath)
			FolderCollection folders = currentFolder.Folders;

			bool folderFound = false;
			foreach (Folder existingFolder in folders)
				if (existingFolder.Name.Equals(folderPointer, StringComparison.InvariantCultureIgnoreCase))
					folderFound = true;
					currentFolder = existingFolder;

			if (!folderFound)
				ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation();
				itemCreationInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
				itemCreationInfo.LeafName = folderPointer;
				itemCreationInfo.FolderUrl = currentFolder.ServerRelativeUrl;
				ListItem folderItemCreated = list.AddItem(itemCreationInfo);
				ctx.Load(folderItemCreated, f => f.Folder);
				currentFolder = folderItemCreated.Folder;
		returnFolder = currentFolder;
	return returnFolder;

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.