Replace a file used by multiple translations

NEW TO SITEFINITY?

The following code replaces a file used by multiple translations.

Native API

using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Text.RegularExpressions;
using Telerik.Sitefinity.Libraries.Model;
using Telerik.Sitefinity.Localization;
using Telerik.Sitefinity.Modules.Libraries;
using Telerik.Sitefinity.Workflow;
public partial class ImageSnippets
{
public static void ReplaceImageNativeAPI(CultureInfo culture, Guid masterImageId, Stream replaceImageStream, string imageFileName, string imageFileExtension)
{
// Ensure we are working in the correct culture.
using (new CultureRegion(culture))
{
var librariesManager = LibrariesManager.GetManager();
// Get the master version of the image
var master = librariesManager.GetImages().FirstOrDefault(i => i.Id == masterImageId);
if (master != null)
{
// Check out the master to get a temp version.
var temp = librariesManager.Lifecycle.CheckOut(master) as Image;
temp.LastModified = DateTime.UtcNow;
temp.MediaFileUrlName = Regex.Replace(imageFileName.ToLower(), @"[^\w\-\!\$\'\(\)\=\@\d_]+", "-");
// Recompiles and validates the url of the image.
librariesManager.RecompileAndValidateUrls(temp);
//if uploadAndReplace is true the method replaces images in all translations with replaceImageStream
//if uploadAndReplace is false the method replaces the image only in the current translation
librariesManager.Upload(temp, replaceImageStream, imageFileExtension, uploadAndReplace: true);
// Checkin the temp and get the updated master version.
// After the check in the temp version is deleted.
master = librariesManager.Lifecycle.CheckIn(temp) as Image;
librariesManager.SaveChanges();
// Publish the Image.
var bag = new Dictionary<string, string>();
bag.Add("ContentType", typeof(Image).FullName);
WorkflowManager.MessageWorkflow(masterImageId, typeof(Image), null, "Publish", false, bag);
}
}
}
}

Want to learn more?

Increase your Sitefinity skills by signing up for our free trainings. Get Sitefinity-certified at Progress Education Community to boost your credentials.

Get started with Integration Hub | Sitefinity Cloud | Sitefinity SaaS

This free lesson teaches administrators, marketers, and other business professionals how to use the Integration hub service to create automated workflows between Sitefinity and other business systems.

Web Security for Sitefinity Administrators

This free lesson teaches administrators the basics about protecting yor Sitefinity instance and its sites from external threats. Configure HTTPS, SSL, allow lists for trusted sites, and cookie security, among others.

Foundations of Sitefinity ASP.NET Core Development

The free on-demand video course teaches developers how to use Sitefinity .NET Core and leverage its decoupled architecture and new way of coding against the platform.

Was this article helpful?