Sharepoint - Creating Nested Folders via Client Object Model
Try not calling clientContext.Load
, for example this works for me:
var folder = list.RootFolder;
clientContext.Load(folder);
clientContext.ExecuteQuery();
folder = folder.Folders.Add("Folder 1");
folder.Folders.Add("Folder 2");
clientContext.ExecuteQuery();
How to create Folder (including nested) via CSOM in SharePoint
/// <summary>
/// Create Folder (including nested) client object
/// </summary>
/// <param name="web"></param>
/// <param name="listTitle"></param>
/// <param name="fullFolderPath"></param>
/// <returns></returns>
public static Folder CreateFolder(Web web, string listTitle, string fullFolderPath)
{
if (string.IsNullOrEmpty(fullFolderPath))
throw new ArgumentNullException("fullFolderPath");
var list = web.Lists.GetByTitle(listTitle);
return CreateFolderInternal(web, list.RootFolder, fullFolderPath);
}
private static Folder CreateFolderInternal(Web web, Folder parentFolder, string fullFolderPath)
{
var folderUrls = fullFolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string folderUrl = folderUrls[0];
var curFolder = parentFolder.Folders.Add(folderUrl);
web.Context.Load(curFolder);
web.Context.ExecuteQuery();
if (folderUrls.Length > 1)
{
var folderPath = string.Join("/", folderUrls, 1, folderUrls.Length - 1);
return CreateFolderInternal(web, curFolder, folderPath);
}
return curFolder;
}
Usage
using (var ctx = new ClientContext("https://contoso.intranet.com/"))
{
var folder = CreateFolder(ctx.Web, "Shared Documents", "FolderA/SubFolderA/SubSubFolderA");
}
How about something like this:
public static Folder EnsureFolder(ClientContext ctx, Folder ParentFolder, string FolderPath)
{
//Split up the incoming path so we have the first element as the a new sub-folder name
//and add it to ParentFolder folders collection
string[] PathElements = FolderPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
string Head = PathElements[0];
Folder NewFolder = ParentFolder.Folders.Add(Head);
ctx.Load(NewFolder);
ctx.ExecuteQuery();
//If we have subfolders to create then the length of PathElements will be greater than 1
if (PathElements.Length > 1)
{
//If we have more nested folders to create then reassemble the folder path using what we have left i.e. the tail
string Tail = string.Empty;
for (int i = 1; i < PathElements.Length; i++)
Tail = Tail + "/" + PathElements[i];
//Then make a recursive call to create the next subfolder
return EnsureFolder(ctx, NewFolder, Tail);
}
else
//This ensures that the folder at the end of the chain gets returned
return NewFolder;
}
and then you can call it with following:
ctx.Load(TargetList.RootFolder);
ctx.ExecuteQuery();
Folder NewFolder = EnsureFolder(ctx, TargetList.RootFolder, "/Folder1/Folder2/Folder3");