Question

How to Create nested folder in sharepoint through c# code ? For Example, I have String like "Shared Documents/Folder1/Folder2/Folder3" and I want to create that folders or skip if folders are already exists, through c# code. Any suggestion or code is highly appreceated.

Was it helpful?

Solution

How to create nested Folder using SharePoint SSOM

internal static class SPFolderExtensions
{
    /// <summary>
    /// Ensure SPFolder
    /// </summary>
    /// <param name="web"></param>
    /// <param name="listTitle"></param>
    /// <param name="folderUrl"></param>
    /// <returns></returns>
    public static SPFolder CreateFolder(this SPWeb web, string listTitle, string folderUrl)
    {
        if (string.IsNullOrEmpty(folderUrl))
            throw new ArgumentNullException("folderUrl");
        var list = web.Lists.TryGetList(listTitle);
        return CreateFolderInternal(list, list.RootFolder, folderUrl);
    }


    private static SPFolder CreateFolderInternal(SPList list, SPFolder parentFolder, string folderUrl)
    {
        var folderNames = folderUrl.Split(new char[] {'/'}, StringSplitOptions.RemoveEmptyEntries);
        var folderName = folderNames[0];

        var curFolder =
            parentFolder.SubFolders.Cast<SPFolder>()
                        .FirstOrDefault(
                            f =>
                            System.String.Compare(f.Name, folderName, System.StringComparison.OrdinalIgnoreCase) ==
                            0);
        if (curFolder == null)
        {
            var folderItem = list.Items.Add(parentFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder,
                                            folderName);
            folderItem.SystemUpdate();
            curFolder = folderItem.Folder;
        }


        if (folderNames.Length > 1)
        {
            var subFolderUrl = string.Join("/", folderNames, 1, folderNames.Length - 1);
            return CreateFolderInternal(list, curFolder, subFolderUrl);
        }
        return curFolder;
    }
}

Key points:

  • Ability to create a nested folder(s)
  • Existing folders will not be affected

Usage

The following example demonstrates how to create the following folder structure under Documents library:

Orders
   |
   Orders A
      |
      Orders A1

Example:

var folder = web.CreateFolder("Documents", "Orders/Orders A/Orders A1");
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top