How to Create Discussions List Topics Programmatically using C# Patterns and Practice (PNP)


Sathish Nadarajan
SharePoint MVP
Published On :   09 Nov 2018
Visit Count
Today :  1    Total :   237



In this article, let us see how to create the topics in a discussion list programmatically using C# Patterns and Practice.

By Using PNP, it is very simple and straight forward to create the discussion topic. The below code is self-explanatory.

 public static void CreateDiscussion()
         {
             try
             {
                 OfficeDevPnP.Core.AuthenticationManager authMgr = new OfficeDevPnP.Core.AuthenticationManager();
 
                 using (var ctx = authMgr.GetSharePointOnlineAuthenticatedContextTenant(siteUrl, userName, password))
                 {
                     Web web = ctx.Web;
                     ctx.Load(web);
                     ctx.Load(web.Lists);
                     ctx.ExecuteQueryRetry();
                     List list = web.Lists.GetByTitle("Discussions List");
                     ctx.Load(list);
                     ctx.ExecuteQueryRetry();
 
                     var topicItem = Microsoft.SharePoint.Client.Utilities.Utility.CreateNewDiscussion(ctx, list, "Test Discussion created by Code");
                     topicItem.Update();
 
                     ctx.ExecuteQuery();
                 }
             }
             catch (Exception ex)
             {
                 System.Console.WriteLine("Exception occurred : " + ex.Message);
                 System.Console.ReadLine();
             }
         }
 

The above code will create the topic as below.

clip_image002

We can later update the topic properties as such it is a simple list item.

Happy Coding,

Sathish Nadarajan.

Categories