Localizing Strings with an Extension Method

February 11 2010 One comment

This is rather uncommon situation, but we needed a way to easily translate strings in our code against the resources deployed in 12\Resources. We created extension methods for that:

public static string Localize(this string source)
{
    return Localize(source, (uint) Thread.CurrentThread.CurrentCulture.LCID);
}

public static string Localize(this string source, uint language)
{
    var pattern = string.Format("^{0}$",
    Regex.Escape("$Resources:FILE,KEY;").
    Replace("FILE", @"\w+").
    Replace("KEY", ".+"));

    if (!Regex.IsMatch(source, pattern)) return source;
    var parts = source.Split(new[] { ':', ',' }, 3);
    var file = parts[1];
    var key = parts[2];
    return SPUtility.GetLocalizedString(
        string.Format("$Resources:{0}", key), file, language);
}

And now when we need to translate a string in our code, we can simply use the following code:

// When we use the extension method, we need to import it first:
// using Sininen.Meteoriitti.SharePoint.Common.Extensions;

var x = "$Resources:ResourceFile,ResourceKey;".Localize();
var y = "$Resources:ResourceFile,ResourceKey;".Localize(
    SPContext.Current.Web.Language);

Popularity: 3% [?]

One comment to “Localizing Strings with an Extension Method”

  1. Stephen K. says:

    Worked great. Thanks!
    Best regards,
    Steve
    http://www.winnipegtreeservice.com

Leave a Reply