Search code examples
c#sharepointcsomshared-directorycreate-directory

In C#, how can I create a folder if it does not exist on a SharePoint site


I am trying to create a microservice in C# which will accept a csv file containing order numbers, digest the csv, connect to sharepoint, create a new folder on sharepoint, and then copy contracts with names corresponding to the order number from whereever they may be (and they probably won't all be in the smae place) to the new folder.

At this point, with help from Stackoverflow, I can successfully get an authentication token from our Sharepoint using a CSOM Authentication Manager. And now I am trying to figure out how to create a the folder. Googling for information on creating Sharepoint folders keeps bringing up the topic of lists, which I don't know anything about and don't even know if I really want or need to know anything about, or whether there might be a different way which works with the site as that's what I'm actually interested in.

So, let's say I have a sharepoint site at https://example.sharepoint.com/sites/MySite.

How can I simply create a folder called "Foo" within a folder called "Bar" which exists in "Shared Documents"?

If I need to know something about lists in order to do this, can I use C# to find the correct list? Or do I need to chase my adminstrator for additional information?


Solution

  • Assuming the AuthenticationManager returns a valid context and the root folder already exists, the following works:

    using Microsoft.SharePoint.Client;
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using AuthenticationManager = SharepointOrderContractExtractor.Clients.AuthenticationManager;
    
    namespace SharePointOrderContractExtractor.Clients
    {
        public class FolderManager
        {
            private readonly AuthenticationManager _authenticationManager;
    
            public FolderManager(
                AuthenticationManager sharepointAuthenticationManager
                )
            {
                _authenticationManager = sharepointAuthenticationManager;
            }
    
            internal Folder EnsureAndGetTargetFolder(string folderPath)
            {
                using ClientContext context = _authenticationManager.GetContext();
    
                List<string> folderNames = folderPath.Split("/").ToList();
                List documents = context.Web.Lists.GetByTitle(folderNames[0]);
                folderNames.RemoveAt(0);
    
                return EnsureAndGetTargetFolder(context, documents, folderNames);
            }
    
            private Folder EnsureAndGetTargetFolder(ClientContext context, List list, List<string> folderPath)
            {
                Folder returnFolder = list.RootFolder;
                return (folderPath != null && folderPath.Count > 0)
                    ? EnsureAndGetTargetSubfolder(context, list, folderPath)
                    : returnFolder;
            }
    
            private Folder EnsureAndGetTargetSubfolder(ClientContext context, List list, List<string> folderPath)
            {
                Web web = context.Web;
                Folder currentFolder = list.RootFolder;
                context.Load(web, t => t.Url);
                context.Load(currentFolder);
                context.ExecuteQuery();
    
                foreach (string folderPointer in folderPath)
                {
                    currentFolder = FindOrCreateFolder(context, list, currentFolder, folderPointer);
                }
    
                return currentFolder;
            }
    
            private Folder FindOrCreateFolder(ClientContext context, List list, Folder currentFolder, string folderPointer)
            {
                FolderCollection folders = currentFolder.Folders;
                context.Load(folders);
                context.ExecuteQuery();
    
                foreach (Folder existingFolder in folders)
                {
                    if (existingFolder.Name.Equals(folderPointer, StringComparison.InvariantCultureIgnoreCase))
                    {
                        return existingFolder;
                    }
                }
    
                return CreateFolder(context, list, currentFolder, folderPointer);
            }
    
            private Folder CreateFolder(ClientContext context, List list, Folder currentFolder, string folderPointer)
            {
                ListItemCreationInformation itemCreationInfo = new ListItemCreationInformation
                {
                    UnderlyingObjectType = FileSystemObjectType.Folder,
                    LeafName = folderPointer,
                    FolderUrl = currentFolder.ServerRelativeUrl
                };
    
                ListItem folderItemCreated = list.AddItem(itemCreationInfo);
                folderItemCreated.Update();
    
                context.Load(folderItemCreated, f => f.Folder);
                context.ExecuteQuery();
    
                return folderItemCreated.Folder;
            }
        }
    }