Programmatically Read Discussion Board & Replies

I searched a lot for Server Object Code in reading Discussion Board Items & Replies. As cannot find one, following is created.

Challenge

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

Steps

This is our Discussion Board.

image

This is the code to retrieve all discussion items.

using (SPSite site = new SPSite(“http://hpvm”))

{

using (SPWeb web = site.OpenWeb())

{

SPList list = web.Lists.TryGetList(“Discussion Board”);

if (list != null)

{

SPQuery query = new SPQuery();

query.ViewFields = “<FieldRef Name=’Title’ />”;

SPListItemCollection itemColl = list.GetItems(query);

foreach (SPListItem item in itemColl)

{

System.Console.WriteLine(item[“Title”].ToString());

}

}

}

}

Make sure the code is returning values like this.

image

Now we are writing the code to return the replies.

private static void GetReplies(SPList list, SPListItem item)

{

SPQuery query = new SPQuery();

query.Folder = item.Folder;

SPListItemCollection collection = list.GetItems(query);

SPListItem replyItem = collection[0];

string body = (string)replyItem[“Body”];

string author = (string)replyItem[“Author”];

System.Console.WriteLine(body);

System.Console.WriteLine(author);

}

Following is the output on running the console application.

image

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.

private static string GetUserName(string author, SPList list)

{

string result = author;

if (author.Contains(“;”))

{

int id = int.Parse(author.Split(‘;’)[0]);

SPUser user = list.ParentWeb.SiteUsers.GetByID(id);

result = user.Name;

}

return result;

}

Now the user name seems to be better.

image

image

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 & Replies. The source code is attached here with the article.

Leave a Reply

Your email address will not be published. Required fields are marked *