I have a folder inside a document library. Inside this folder I need to check the existence of a sub-folder and then, add a document and another folder to it programmatically.

Lets say, my document library has a folder as "TopFolder", then within that I need to check if sub-folder "Project One" exists. If it does not exists, first create it.

And then within "Project One" folder,

i) Add a document &

ii) Create a new folder.

So basically what would be the best way around to add a folder within a folder in a SharePoint document library?

I could do a CAML query and get the "TopFolder" but then how to check the nested folders within that and create new ones ?

  • So, are you expecting the answer with C# or PowerShell example? Sep 10, 2014 at 16:17
  • 1
    @VadimGremyachev I'm doing this in a Application page's code behind, So I am using C#
    – Shaamil
    Sep 11, 2014 at 5:35
  • Have you seen my answer, was it helpful? Sep 16, 2014 at 10:17

2 Answers 2


For uploading a file into a nested folder you could consider the following approach:

How to ensure a nested Folder exist 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 EnsureFolder(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,
            curFolder = folderItem.Folder;

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

Gist: EnsureFolder.cs

The following example demonstrates how to ensure the following folder structure exist under Documents library and upload a file into it:

     A --

Example: how to upload a file into a nested folder

var targetFolder = web.EnsureFolder("Documents", "Orders3/A/A1");
var fileContent = System.IO.File.ReadAllBytes(fileName);
var fileUrl = Path.GetFileName(fileName);
targetFolder.Files.Add(fileUrl, fileContent);

Below code is used to create a folder under document lib with "CurrentMonth Year" if folder does not exists it creates new folder else add items to the folder .

string currentDate = System.DateTime.Now.ToString(Constants.monthDateYearFormat);
string[] splitter = currentDate.Split(' ');
string folderName = splitter[0].ToString() + " " + splitter[2].ToString();

//Check if the Folder is already available in the doc lib                
SPQuery query = new SPQuery();
query.Query = "<Where><And><Eq><FieldRef Name='LinkTitle'/><Value Type='Text'>" + folderName + "</Value></Eq><Eq><FieldRef Name='FSObjType'/><Value Type='Lookup'>1</Value></Eq></And></Where>";

//delete below line for performance
query.ViewAttributes = "Scope=\"RecursiveAll\"";
//Retrieve the items based on Query                
SPListItemCollection items = list.GetItems(query);

//if (!folderExists)
if (items.Count == 0)
                                    //// create a folder under the path specified 

                                    folderItem = list.AddItem(list.RootFolder.ServerRelativeUrl, SPFileSystemObjectType.Folder);

                                    //// set the folder name and update 
                                    folderItem[Constants.folderTitle] = folderName;
                                        SPListItem listItem = list.AddItem(folderItem.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);

                                        folderItem = items[0];
                                        SPListItem listItem = list.AddItem(folderItem.Folder.ServerRelativeUrl, SPFileSystemObjectType.File, null);


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.