Once we required to convert the Sitecore Media Item to a disk file (Save media item as a physical file on server). Sitecore does not provide any API to do this directly.
Below is the code to do it, thought to post it if can help others..
Below is the code to do it, thought to post it if can help others..
string mediaItemPath = "/sitecore/media library/Images/myimage";
string diskFolderPath = @"D:\Sitecore-Media\";
MediaItem mediaItem = (MediaItem)Sitecore.Context.Database.GetItem(mediaItemPath);
ConvertMediaItemToFile(mediaItem, diskFolderPath);
public static void ConvertMediaItemToFile(MediaItem mediaItem, string folderName)
{
if (mediaItem.InnerItem["file path"].Length > 0)
return;
string fileName = folderName + mediaItem.Name + "." + mediaItem.Extension;
var blobField = mediaItem.InnerItem.Fields["blob"];
Stream stream = blobField.GetBlobStream();
if (stream == null)
{
return;
}
string relativePath = Sitecore.IO.FileUtil.UnmapPath(fileName);
try
{
SaveToFile(stream, fileName);
stream.Flush();
stream.Close();
}
catch (Exception ex)
{
Log.Error(string.Format("Cannot convert BLOB stream of '{0}' media item to '{1}' file", mediaItem.MediaPath, relativePath));
}
}
private static void SaveToFile(Stream stream, string fileName)
{
byte[] buffer = new byte[8192];
using (FileStream fs = File.Create(fileName))
{
int length;
do
{
length = stream.Read(buffer, 0, buffer.Length);
fs.Write(buffer, 0, length);
}
while (length > 0);
fs.Flush();
fs.Close();
}
}












