There is a slight difference to looping through discussion board items as compared to standard list items. The main difference is having to use SPList.Folders and not SPList.Items
As a result of that, extracting any attachments to the SPList.Folders is not very obvious.
I had been trying to get the attachment as an SPFile object so I can convert it into binary and store it in the SQL Server database as an "image" (binary object). However I seem to only be able to get the filename as a string and not as an SPFile object.
Here's the code I used:
SPWeb mySite = SPContext.Current.Web;
SPList oList = mySite.Lists["DiscussionBoardListName"];
SPListItemCollection oListItems = oList.Folders;
for (int i = 0; i < oListItems.Count; i++)
{
SPListItem item = oListItems[i];
if (item.Attachments.Count > 0)
{
for (int j = 0; j < item.Attachments.Count; j++)
{
// item.Attachments.UrlPrefix - gives the path to the attachment as a string
// item.Attachments[j]; - gives the attachment name as a string
// together I couldn't get it into a SPFile object.
// I tried to use the URL method to read the file Url into stream,
// but I get an access denied error
}
}
}
To get the attachments into SPFile format, I had to get the parent folder into an SPFolder object and loop through the SPFolder and get the contents as SPFile objects.
for (int i = 0; i < oListItems.Count; i++)
{
SPListItem item = oListItems[i];
SPFolder attachmentsFolder = item.ParentList.RootFolder.SubFolders["Attachments"].SubFolders[item.ID.ToString()];
if (item.Attachments.Count > 0)
{
for (int j = 0; j < item.Attachments.Count; j++)
{
SPFile file = attachmentsFolder.Files[j];
// then do what you want with the SPFile object
}
}
}