I am trying to programmatically (C# CSOM)create folders inside a custom List inside one of my SharePoint 2013 Online site.I have tried 2 code solutions , but both of them are behaving in a weird manner:
This code works perfectly for creating folders inside document library but not for Lists
var list = ctx.Web.Lists.GetByTitle(listName); var folder = list.RootFolder; ctx.Load(folder); ctx.ExecuteQuery(); folder = folder.Folders.Add(folderName); ctx.ExecuteQuery();
The below code also not working:
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder; itemCreateInfo.LeafName = folderName; ListItem oListItem; var list = ctx.Web.Lists.GetByTitle(listName); oListItem = list.AddItem(itemCreateInfo); oListItem.Update(); ctx.ExecuteQuery();
Both the methods works without error in the console,. but when i browse to the list i am not able to see the Folders. When i try manually to create folder through UI with the same name , i get the message a folder with name already exists.
Edit: I am able to add folder through UI and it is visible. The user credentials passed are of site collection administrator. I have tried in different browsers. Also, 1 more thing in site contents the Last modified time also is not getting changed once i create folder through code.
UPDATE: Got it Fixed. The problem was with the folderName parameter passed to the method. I was reading the folderName from Excel sheet and it had a space appended to its end, that was breaking the code in mine. The Code 1 works only for Libraries not for Lists, Code 2 works fine, lesson learned at least for me. Make Sure to trim the folderName before passing to leafName(i.e itemCreateInfo.LeafName = folderName;
).
My final working Code:
private static void CreateFolder(string listName, string folderName, ClientContext ctx)
{
try
{
List list = ctx.Web.Lists.GetByTitle(listName);
ListItemCreationInformation info = new ListItemCreationInformation();
info.UnderlyingObjectType = FileSystemObjectType.Folder;
info.LeafName = folderName.Trim();//Trim for spaces.Just extra check
ListItem newItem = list.AddItem(info);
newItem["Title"] = folderName;
newItem.Update();
ctx.ExecuteQuery();
Console.WriteLine("{0} folder Created", folderName);
}
catch (Exception Ex)
{
Console.WriteLine(Ex.Message);
}
}