Search code examples
c#sitecorememorystreamsitecore-media-library

how to add a file to a MediaItem using SetStream?


I have the following situation:

  • I have a file on the server ("file");
  • I have an existing item in the Media Library to which this file must be attached ("item").

I tried using the following:

var stream = new MemoryStream(file);
var mediaItem = MediaManager.GetMedia(item);
var mediaStream = new MediaStream(stream, extension, item);

mediaItem.SetStream(mediaStream);

But the last operation ALWAYS fail throwing an exception saying "Cannot access closed stream", even though the stream appears to be open before running the last command.

Can someone tell me what I'm doing wrong?


Solution

  • Try to use MediaManager.Creator.AttachStreamToMediaItem method:

    FileStream fileStream = new FileStream(fileName, FileMode.Open, FileAccess.Read);
    MediaManager.Creator.AttachStreamToMediaItem(fileStream, "mediaItemPath", fileName, options)