CSOM: Create Duplicate View in SharePoint List

  1. //Author: Shantha Kumar T      
  2. //Method used: SP.List.saveAsNewView(string oldViewGuid, string newName, boolean privateView, string uri)     
  3. //Paramteres:      
  4. ////oldViewGuid: Guid of the view  in string format    
  5. ////newName: Name for the new view      
  6. ////privateView: Boolean value to set private view or public view       
  7. ////uri: url for new view      
  8. //Supports: SharePoint 2013 + and SharePoint Online     
  9.   
  10. string weburl = "https://sharepointsite";    
  11. string listTitle="Test List";    
  12. Guid guidOldView = new Guid("59A88256-510F-4C66-836E-E91C6D30A73A");    
  13. string newViewName = "Duplicate View";    
  14. string newViewUrl = "duplicateview.aspx";    
  15.     
  16. CreateDuplicateView(credentials, weburl, listTitle, guidOldView, newViewName, newViewUrl);    
  17.   
  18.       
  19. private static void CreateDuplicateView(ICredentials credentials, string weburl, string listTitle, Guid guidOldView, string newViewName, string newViewUrl)    
  20. {    
  21.     using (ClientContext ctx = new ClientContext(weburl))    
  22.     {    
  23.         ctx.Credentials = credentials;    
  24.         Web oweb = ctx.Web;    
  25.         ListCollection lists = oweb.Lists;    
  26.         List targetList = lists.GetByTitle(listTitle);    
  27.     
  28.         ClientResult<string>  res = targetList.SaveAsNewView(guidOldView.ToString(), newViewName, false, newViewUrl);                   
  29.     
  30.         ctx.ExecuteQuery();    
  31.                             
  32.         Console.WriteLine("View Successfully created in url: "+ res.Value);    
  33.     }    
  34.     Console.WriteLine("Press any key to exit...");    
  35.     Console.Read();    
  36. }