3

How can I create a folder in SharePoint 2013 programmatically?

This is how I done the creation of a List. Is it possible to do it with folders?

    public static SPList GetOrCreateList(ref SPWeb web, SPList sourceList, string name, string description = null)
    {
        Guid ListGuid = new Guid();
        SPList _List = web.Lists.TryGetList(name);
        if (_List == null)
        {
            ListGuid = web.Lists.Add(name, description, (SPListTemplateType)sourceList.BaseTemplate);
            web.Update();
            _List = web.Lists[ListGuid];
        }
        return _List;
    }
4

Considering Folder is at one level, and not folders inside folders. This code will work.

Also make sure, in list setting -> Advance Settings -> Make "New Folder" command available? is set to Yes.

    public SPFolder GetOrCreateFolder(ref SPWeb web, SPList sourceList, string listName, string folderName)
    {
        SPFolder folder = null;
        if (sourceList == null)
        {
            folder = web.Folders[listName];
            if (folder != null)
            {
                if(!folder.SubFolders[folderName].Exists)
                    folder.SubFolders.Add(folderName);
                else
                    folder = folder.SubFolders[folderName];
            }
        }
        return folder;
    }
  • but is folder = web.Folders[listName]; really getting one specific folder or all folders for a list? – Snickbrack Sep 28 '16 at 8:12
  • it will give you the root folder of list – Gaurravs Sep 28 '16 at 8:21
  • what do I have to do if I want to get a folder for specific name? – Snickbrack Sep 28 '16 at 8:41
  • I have updated the code, only else block was required – Gaurravs Sep 28 '16 at 8:47
  • welcome, have nice day too – Gaurravs Sep 28 '16 at 9:17
0

Try:

String url = site.Lists["LIST NAME"].RootFolder.ServerRelativeUrl.ToString();
SPFolderCollection folders = site.GetFolder(url).SubFolders; 

//Create new folder
folders.Add("FOLDER NAME");

Hope this helps

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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