21

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:

  1. 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();
    
  2. 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);
            }
        }
Unnie
  • 8,819
  • 1
  • 22
  • 36

3 Answers3

14

Try adding the following code for folder creation.

 //Enable Folder creation for the list
 list.EnableFolderCreation = true;
 list.Update();
 context.ExecuteQuery();

 //To create the folder
 ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation();

 itemCreateInfo.UnderlyingObjectType = FileSystemObjectType.Folder;
 itemCreateInfo.LeafName = folderName;

 ListItem newItem = list.AddItem(itemCreateInfo);
 newItem["Title"] = folderName;
 newItem.Update();
 clientContext.ExecuteQuery();
Aveenav
  • 4,199
  • 1
  • 14
  • 13
  • This will only work if the current user has Contribute role, otherwise it thows an error. Edit is needed. – Emaborsa May 15 '20 at 08:20
4

This is a old post, however after several attempts with other server results, I came across this post which led me to my final answer, so I wanted to update.

NOTE: This is part of a process where I'm uploaded from a Local Drive to SharePoint, So the myListLibrary has already been loaded, and the myLocalFile.RelativePath is simply a string that looks something like "\Temp\Folder1\Folder2\myFile.txt"

This is using CSOM ..

//The Target Folder may not exists so we have to account for 
//that before uploading the file. So we start with the RootFolder
Microsoft.SharePoint.Client.Folder myRemoteFolder = myListLibrary.RootFolder;

//Now for each Folder in the File's Path, we switch to that Folder, 
//and create if needed.
foreach (string myFolder in myLocalFile.RelativePath.Replace(myLocalFile.Name, "").Split(new char[] { '\\' }, StringSplitOptions.RemoveEmptyEntries))
{
  mySPClientContext.Load(myRemoteFolder);
  myRemoteFolder.Folders.Add(myFolder);
  mySPClientContext.ExecuteQuery();

  myRemoteFolder = mySPClientContext.Web.GetFolderByServerRelativeUrl(myRemoteFolder.ServerRelativeUrl + "/" + myFolder);
}

Not only did this create my folders perfectly.. but didn't seem to care if they were already there or not.

da_jokker
  • 441
  • 3
  • 8
1

Alternatively you can use relative path API as well. This works well to create sub folder recursively.

Refer the code:

 Folder _folder = _ctx.Web.GetFolderByServerRelativeUrl("myDocLib\\Folder1");
 _folder.AddSubFolder("Folder L2");
 _ctx.Load(_folder);
 _ctx.ExecuteQuery();

FYI: _ctx is clientContext object

DvG
  • 2,332
  • 2
  • 13
  • 31