Wednesday, February 13, 2019

Create folder in SharePoint list (SharePoint 2010, 2013, 2016)

So, we continue to work with basic operations, today is another piece of code in which we are using CSOM create a folder in the program list. And as usual by tradition I use Visual studio.

The main advantage of this code is the use of C#, which means such wonderful features are available as Custom Timer Job, Event Reciever and much more. In my console project I using following reference and code:

using Microsoft.SharePoint.Client;

using (var clientContext = new ClientContext("http://sp/sites/test"))
            {
                string folderName = "test";
                var list = clientContext.Web.Lists.GetByTitle("ListBase");
                list.EnableFolderCreation = true;

                clientContext.Load(list);
                clientContext.Load(list.RootFolder);
                clientContext.Load(list.RootFolder.Folders);
                clientContext.ExecuteQuery();

                var folderCollection = list.RootFolder.Folders;

                foreach (var folder in folderCollection)
                {
                    if (folder.Name == folderName)
                    {
                        clientContext.Load(folder.Files);
                        clientContext.ExecuteQuery();
                    }
                    else
                    {
                        var itemCreateInfo = new ListItemCreationInformation
                        {
                            UnderlyingObjectType = FileSystemObjectType.Folder,
                            LeafName = folderName
                        };
                        var newItem = list.AddItem(itemCreateInfo);
                        newItem["Title"] = folderName;
                        newItem.Update();
                        clientContext.ExecuteQuery();
                        break;
                    }
                }
            }
Happy Coding!

No comments:

Post a Comment