How to create SharePoint Folders programmatically?
-
09-12-2020 - |
Question
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;
}
Solution
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;
}
OTHER TIPS
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
Licensed under: CC-BY-SA with attribution
Not affiliated with sharepoint.stackexchange