Add attachments to forum posts
To add an attachment to a post, you must perform the following:
-
Get the specified post.
Get an instance of the specified post. For more information, see For developers: Query forum posts. -
Create a
Documentmedia item.
Create aDocumentmedia item as a container for the attachment. TheDocumentmedia item can be used for storage of any types of files (images, videos, archives, documents). For more information aboutDocumentmedia items and their API, see For developers: CRUD operations with documents and files.NOTE: When calling the
GetForumLibrarymethod of theForumobject, it returns a system library for the forum. Use this library to upload the attachments to. For more information, see For developers: Forums. -
Attach the media item.
To attach the media item to the post, you must call theAddAttachmentmethod of theForumPostinstance and pass the media item as an argument.NOTE: The live version of the item is added as an attachment.
-
Save the changes.
Save the changes to the manager.
Here is a code example:
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using Telerik.Sitefinity;
using Telerik.Sitefinity.Forums;
using Telerik.Sitefinity.Forums.Model;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Workflow;
namespace SitefinityWebApp
{
public class AddAttachmentsToForumPosts_AddAttachmentToPost
{
public void AddAttachmentToPost(Guid postId, FileInfo documentFile)
{
ForumsManager forumsManager = ForumsManager.GetManager();
ForumPost post = forumsManager.GetPost(postId);
Guid forumLibraryId = post.Forum.GetForumLibrary().Id;
//Create the document.
Guid documentId = Guid.Empty;
App.WorkWith().DocumentLibrary(forumLibraryId).CreateDocument()
.Do(document =>
{
documentId = document.Id;
document.Title = documentFile.Name;
document.DateCreated = DateTime.UtcNow;
document.PublicationDate = DateTime.UtcNow;
document.LastModified = DateTime.UtcNow;
document.Urls.Clear();
document.UrlName = Regex.Replace(documentFile.Name.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
}).CheckOut()
.UploadContent(documentFile.OpenRead(), documentFile.Extension)
.CheckIn()
.Publish()
.SaveChanges();
//Add the attachment
post.AddAttachment(App.WorkWith().Document(documentId).GetLive().Get());
forumsManager.SaveChanges();
}
}
}