Programmatically Read Discussion Board & Replies

I searched a lot for Server Object code in reading Discussion Board items and replies. Since I was unable to find one, I created the following.

Challenge

You need to programmatically get all discussion items along with their replies.

Procedure

1.
This is our Discussion Board.

discussion board

This is the code to retrieve all discussion items.

  1. using (SPSite site = new SPSite("http://hpvm"))  
  2. {  
  3.       using (SPWeb web = site.OpenWeb())  
  4.       {  
  5.             SPList list = web.Lists.TryGetList("Discussion Board");  
  6.             if (list != null)  
  7.             {  
  8.                   SPQuery query = new SPQuery();  
  9.                   query.ViewFields = "<FieldRef Name='Title' />";  
  10.   
  11.                   SPListItemCollection itemColl = list.GetItems(query);  
  12.                   foreach (SPListItem item in itemColl)  
  13.                   {  
  14.                         System.Console.WriteLine(item["Title"].ToString());  
  15.                   }  
  16.             }  
  17.       }  
  18. }  
2. Make sure the code is returning values like this.

discussion topic 1

Now we are writing the code to return the replies.
  1. private static void GetReplies(SPList list, SPListItem item)  
  2. {  
  3.       SPQuery query = new SPQuery();  
  4.       query.Folder = item.Folder;  
  5.   
  6.       SPListItemCollection collection = list.GetItems(query);  
  7.   
  8.       SPListItem replyItem = collection[0];  
  9.       string body = (string)replyItem["Body"];  
  10.       string author = (string)replyItem["Author"];  
  11.   
  12.       System.Console.WriteLine(body);  
  13.       System.Console.WriteLine(author);  
  14. }  
The following is the output on running the console application.

system account

3. You can see the Author is returned mixing with ID. You can use the following method to extract the correct User Name from the string.
  1. private static string GetUserName(string author, SPList list)  
  2. {  
  3.       string result = author;  
  4.   
  5.       if (author.Contains(";"))  
  6.       {  
  7.             int id = int.Parse(author.Split(';')[0]);  
  8.             SPUser user = list.ParentWeb.SiteUsers.GetByID(id);  
  9.             result = user.Name;  
  10.       }  
  11.   
  12.       return result;  
  13. }  
4. Now the user name seems to be better.

user status

note

I am creating a Console Application to retrieve the same.

References

    http://bit.ly/1tIX5NV

Summary

In this article we have explored how to fetch Discussion Board Items and Replies. The source code is attached here with the article. 

Up Next
    Ebook Download
    View all
    Learn
    View all