Thursday, September 11, 2014

Sharepoint Client Object model create Folders in Document Library or list programmatically

Below methods will create a Folder or Subfolders in SharePoint library from client side.
Providing the relative path you can create the subfolder e.i  folder inside a folder as well

DDL used are Microsoft.Sharepoint.client and Microsoft.Sharepoint.Client.runtime.


public void CreateListFolder(string siteUrl, string listName, string relativePath, string folderName)
        {
            using (ClientContext clientContext = new ClientContext(siteUrl))
            {
                Web web = clientContext.Web;
                List list = web.Lists.GetByTitle(listName);
                list.EnableFolderCreation = true;
              
                ListItemCreationInformation newItem = new ListItemCreationInformation();
                newItem.UnderlyingObjectType = FileSystemObjectType.Folder;
                newItem.FolderUrl = siteUrl +"/"+ listName;
                if (!relativePath.Equals(string.Empty))
                {
                    newItem.FolderUrl += "/" + relativePath;
                }
                newItem.LeafName = folderName;
                ListItem item = list.AddItem(newItem);
                 //updating the metadata for the folder
                item["Col1"] = "Folder Property-1";
                item.Update();
                clientContext.Load(list);
                clientContext.ExecuteQuery();
            }


You can call the method a below
CreateListFolder(@"http://WebApplication:777", "ListA", "", "FolderA");



Other way of creating it is


  public void CreateLibraryFolder2()
        {
            using (var clientContext = new ClientContext(@"http://WebApplication:777/"))
            {
                var web = clientContext.Web;
                var lst = web.Lists.GetByTitle("Shared Documents");
                var fld1 = lst.RootFolder.Folders.Add("FirstLevel2");
                var fld2 = fld1.Folders.Add("SecondLevel2");      
                fld1.Update();
                fld2.Update();

                var t1 = lst.RootFolder.Folders.Add("FirstLevel7");
                var t2 = t1.Folders.Add("SecondLevel7");
                fld1.Update();
                fld2.Update();
                               

                clientContext.ExecuteQuery();
               
            }
        }

        
Thanks to the references found by googling :)

4 comments:

  1. Hi
    Have you tried the same code with any custom list?

    ReplyDelete
    Replies
    1. Sorry for the wrong question.
      Actually i am asking about will this code works for any custom list for creating subfolders?

      Delete
  2. We are trying to create folder & file in sharepoint 2013 using client object model.
    We got success to create files on sharepoint, but while creating folder we are getting "401 unauthorized" error.

    ReplyDelete