We are trying to programmatically attach Media File to a Media Item at the latest version. Our requirement is to programmatically extract the file (System.IO.File) from the Local System and attach to Sitecore. Sitecore's Attach Media Code is shown below:

Pipeline.Start("attachFile", new AttachArgs(HttpPostedFile File, item));

Sitecore code accepts only files as HttpPostedFile type. Is there any way to convert System.IO.File type file to the HttpPostedFile type programmatically or is there any way to attach the System.IO.File type files to the Sitecore media item?

1 Answer 1


Here is code directly from Sitecore documentation and link to docs:


var options = new Sitecore.Resources.Media.MediaCreatorOptions();
options.Database = Sitecore.Configuration.Factory.GetDatabase("master");
options.Language = Sitecore.Globalization.Language.Parse(   Sitecore.Configuration.Settings.DefaultLanguage);
options.Versioned = Sitecore.Configuration.Settings.Media.UploadAsVersionableByDefault;
options.Destination = "/sitecore/media library/images/Sample";
options.FileBased = Sitecore.Configuration.Settings.Media.UploadAsFiles;

var creator = new Sitecore.Resources.Media.MediaCreator();

Sitecore.Data.Items.MediaItem sample =  creator.CreateFromFile(@"C:\temp\sample.jpg",options);

Code is for Sitecore 9 so it might be slightly different for other versions. You can use version selector of Sitecore documentation in bottom left of your screen when you accept cookies.

That code created new media item. If you want to attach media to existing item, best read your file into stream and use media.SetStream method:

Sitecore.Resources.Media.Media media = MediaManager.GetMedia(mediaItem);
media.SetStream(memoryStream, ".pdf"); // or other extension
  • Thanks for the answer. This code deletes all the previous versions and start from Version 1. Our requirement is to attach at the latest version only.
    – Sylesh JL
    Commented Sep 22, 2022 at 14:01
  • Is your media item a Versioned item? What is its template?
    – Marek Musielak
    Commented Sep 22, 2022 at 14:03
  • Yes its versioned media item. - versioned/pdf
    – Sylesh JL
    Commented Sep 22, 2022 at 15:23

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.