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);
		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;
}

4 thoughts on “Create a nested folder structure inside SharePoint with CSOM

  1. Thanks for the code . it helped me a lot. It was very helpfull and running code without any issues.

  2. Valuable code. Especially line
    itemCreationInfo.FolderUrl = currentFolder.ServerRelativeUrl;
    helped me a lot. Many reputable sites suggest using absolute URL here, which is wrong and leads to errors. Thank you.

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.