Friday 21 March 2014

Programmatically create a folder in a document library and in a list

Programmatically create a folder in a document library


I was able to successfully create a folder in a document library using this code:

SPList list = web.Lists.TryGetList("ListTitle");
SPFolderCollection folderColl = list.RootFolder.SubFolders;
SPFolder newFolder = folderColl.Add(FolderUrl);

FolderUrl means one of the following:
  • "/Document Library/Folder1"
    Creates a folder named “Folder1” under “Document Library”…
  • "/Document Library/Folder1/Folder11"
    Creates a folder named “Folder11” under “Folder1” in “Document Library”…
  • "/Subsite/Document Library/Folder1"
    Creates a folder named “Folder1” under “Document Library” in a sub site…
  • "/Subsite/Document Library/Folder1/Folder11" 
    Creates a folder named “Folder11” under “Folder1” in “Document Library” in a sub site… 

Here is the desired result:



Programmatically create a folder in a list

So after we can create a folder in a SharePoint document library we now can create them in SharePoint lists.

I was able to successfully create a folder in a SharePoint list using this code :

SPList list = web.Lists.TryGetList("ListTitle");
SPListItem newFolderItem = list.Items.Add(completeFolderUrl, SPFileSystemObjectType.Folder);
newFolderItem["Title"] = "TitleOfTheFolder";
newFolderItem.Update();

completeFolderUrl means one of the following:
  • "/lists/Custom List"
    The folder is created under “Custom List”…
  • "/lists/Custom List/Folder1"
    The folder is created under “Folder1” in “Custom List”…
  • "/aboutus/lists/Custom List"
    The folder is created under “Custom List” in a sub site…
  • "/aboutus/lists/Custom List/Folder1"
    The folder is created under “Folder1” in “Custom List” in a sub site…
Important: The folder didn’t create for me when my “completeFolderUrl” ended with a slash ‘/’.

This is the desired result :





No comments:

Post a Comment