Copying List, list fields and list Items using CSOM
Softree Technology > Blogs > SharePoint > Copying List, list fields and list Items using CSOM

Copying List, list fields and list Items using CSOM

  • Posted by: Softree Technology

In this SharePoint blog, we are going to program how we can clone/copy a list, list fields and list Items within a single site programmatically using .Net client object model (CSOM) in SharePoint Online.

Before we start, we need to create a console application in Visual Studio. We must refer the piece of code & snapshot provided below for better understanding of the operation of program.

Step-1: First we need to input Site URL & the credentials for site and the List name which we want to copy.

Step-2: Set the credentials for site.

Step-3: Creating the destination List by referring the base ID of source list.

Step-4: Creating the field for destination list and adding the field value from the field collection of source list.

Step-5: Retrieve all the items from the source list and adding it to the corresponding field of destination list.

      static void Main(string[] args)
        {
            #region [Variables]
            string siteURL = string.Empty;
            string username = string.Empty;
            string password = string.Empty;
            string sorList = string.Empty;
            string newList = string.Empty;
            #endregion #region [Constant Variables]
            const string ctSiteURL = "Provide a valid source Site URL: ";
            const string ctUsername = "Enter username: ";
            const string ctPassword = "Enter password: ";
            const string ctSorList = "Enter the exist source Listname: ";
            const string ctNewList = "Enter the new Listname you want to create: ";
            #endregion

            #region [SP Variables]
            Web spWeb = null;
            List spSrcList = null;
            List spNewList = null;
            FieldCollection spFieldColl = null;
            #endregion

            #region [ConsoleMessages]
            Console.Write(ctSiteURL);
            siteURL = Console.ReadLine();

            Console.Write(ctUsername);
            username = Console.ReadLine();

            Console.Write(ctPassword);
            password = Console.ReadLine();

            Console.Write(ctSorList);
            sorList = Console.ReadLine();

            Console.Write(ctNewList);
            newList = Console.ReadLine();
            #endregion

        using (ClientContext ctx = new ClientContext(siteURL))
        {
            SecureString securstr = new SecureString();
            foreach (char ch in password)
            {
                securstr.AppendChar(ch);
            }
            ctx.Credentials = new SharePointOnlineCredentials(username, securstr);

            spWeb = ctx.Web;

            ctx.Load(ctx.Web);
            spSrcList = ctx.Web.Lists.GetByTitle(sorList);

            ctx.Load(spSrcList);
            ctx.ExecuteQuery();

            spNewList = CreateSPList(ctx, spWeb, spSrcList, newList);

            spFieldColl = CopySPListFields(ctx, spSrcList, spNewList);

            CreateSPListItems(ctx, spSrcList, spNewList, spFieldColl);

            Console.WriteLine("The list" + " " + newList + " " + "Translated Successfully");
            Console.ReadLine();
        }
    }

    /// <summary>
    /// This function is used to create the list in destination site 
    /// based on source site list information
    /// </summary>
    /// <param name="ctx"></param>
    /// <param name="web"></param>
    /// <param name="srcList"></param>
    /// <param name="newList"></param>
    /// <returns></returns>
    private static List CreateSPList(ClientContext ctx, Web web, List srcList, string newList)
    {
        #region [Variables]
        ListCreationInformation destList = null;
        List spNewList = null;

        int baseid = -1;
        #endregion

        try
        {
            baseid = srcList.BaseTemplate;

            destList = new ListCreationInformation();
            destList.Title = newList;
            destList.TemplateType = baseid;

            web.Lists.Add(destList);
            spNewList = ctx.Web.Lists.GetByTitle(destList.Title);

            ctx.Load(srcList);
            ctx.ExecuteQuery();

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

        return spNewList;
    }

    /// <summary>
    /// This function is used to copy the fields/columns from source list to
    /// destination list
    /// </summary>
    /// <param name="ctx"></param>
    /// <param name="spSrcList"></param>
    /// <param name="spNewList"></param>
    /// <returns></returns>
    private static FieldCollection CopySPListFields(ClientContext ctx, List spSrcList, List spNewList)
    {
        #region [Variables]
        FieldCollection spFieldColl = null;
        string xmlValue = string.Empty;
        #endregion

        try
        {
            spFieldColl = spSrcList.Fields;

            ctx.Load(spFieldColl);
            ctx.ExecuteQuery();

            foreach (Field field in spFieldColl)
            {
                try
                {
                    if (!field.Hidden)
                    {
                        xmlValue = field.SchemaXml;
                        spNewList.Fields.AddFieldAsXml(xmlValue, true, AddFieldOptions.AddToDefaultContentType);
                        spNewList.Update();
                        ctx.ExecuteQuery();
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }

        return spFieldColl;
    }

    /// <summary>
    /// This function is used to create the List items in destination list
    /// </summary>
    /// <param name="ctx"></param>
    /// <param name="spSrcList"></param>
    /// <param name="spNewList"></param>
    /// <param name="spFieldColl"></param>
    private static void CreateSPListItems(ClientContext ctx, List spSrcList, List spNewList, FieldCollection spFieldColl)
    {
        #region [Variables]
        CamlQuery spCamlQuery = null;
        ListItemCollection spListItems = null;
        ListItemCreationInformation spItemCreateInfo = null;
        ListItem spNewItem = null;
        #endregion

        try
        {
            spCamlQuery = new CamlQuery();
            spCamlQuery.ViewXml = "<View/>";

            spListItems = spSrcList.GetItems(spCamlQuery);
            ctx.Load(spListItems);
            ctx.ExecuteQuery();

            foreach (ListItem item in spListItems)
            {
                try
                {
                    spItemCreateInfo = new ListItemCreationInformation();
                    spNewItem = spNewList.AddItem(spItemCreateInfo);
                    spNewItem["Title"] = item["Title"];
                    spNewItem.Update();
                    ctx.ExecuteQuery();
                    foreach (Field field in spFieldColl)
                    {
                        try
                        {
                            if (!field.Hidden)
                            {
                                spNewItem[field.Title] = item[field.Title];
                                spNewItem.Update();
                            }
                        }
                        catch (Exception e)
                        {
                            Console.WriteLine(e);
                        }
                    }
                    ctx.ExecuteQuery();
                }
                catch (Exception e)
                {
                    Console.WriteLine(e);
                }
            }            
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex);
        }
     }
  }
}

After running the code, we can see the destination list is created in the site content of the Site which we have provided while running the program.

Figure 1

Figure 2

Figure1: – This figure shows how the source list was created.

Figure2: -This figure shows how the destination list is created after running the above code.

Keywords:

  • Copying List, list fields and list Items using CSOM.
  • How to copy a List within a single site using CSOM.
  • Copying a list, list items & list fields of SharePoint site using CSOM.
  • Clone a list within a SharePoint site using .Net client object model (CSOM).
  • Programmatically how to copy list, list items & list field using CSOM.
Author: Softree Technology

Leave a Reply