Add attachments to forum posts

To add an attachment to a post, you must perform the following:

  1. Get the specified post.
    Get an instance of the specified post. For more information, see For developers: Query forum posts.

  2. Create a Document media item.
    Create a Document media item as a container for the attachment. The Document media item can be used for storage of any types of files (images, videos, archives, documents). For more information about Document media items and their API, see For developers: CRUD operations with documents and files.

    NOTE: When calling the GetForumLibrary method of the Forum object, it returns a system library for the forum. Use this library to upload the attachments to. For more information, see For developers: Forums.

  3. Attach the media item.
    To attach the media item to the post, you must call the AddAttachment method of the ForumPost instance and pass the media item as an argument.

    NOTE: The live version of the item is added as an attachment.

  4. Save the changes.
    Save the changes to the manager.

Here is a code example:

C#
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();
        }
    }
}
Want to learn more?
Enhance your Sitefinity skills by enrolling in free training sessions. Become Sitefinity certified through Progress Education Community to strengthen your professional credentials.
New to Sitefinity?