Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Quickly switch to a different culture to perform work without
- // switching the entire thread
- // Usage:
- // Console.WriteLine("Starts in English : {0}", DateTime.Now);
- //
- // Culture.As(Culture.Type.German, () => {
- // Console.WriteLine("Now in German : {0}", DateTime.Now);
- // });
- //
- // Console.WriteLine("English again : {0}", DateTime.Now);
- /// <summary>
- /// Handles working in different cultures for periods of times
- /// </summary>
- public class Culture {
- /// <summary>
- /// Types of cultures to use
- /// </summary>
- public enum Type {
- English,
- German,
- Spanish
- }
- /// <summary>
- /// Performs work in a different culture
- /// </summary>
- public static void As(Culture.Type type, Action work) {
- string culture = Culture._GetCultureString(type);
- Culture.As(culture, work);
- }
- /// <summary>
- /// Performs work in a different culture
- /// </summary>
- public static void As(string culture, Action work) {
- culture = (culture ?? string.Empty).Trim();
- //get the existing cultures to revert
- var original = new {
- culture = Thread.CurrentThread.CurrentCulture,
- uiCulture = Thread.CurrentThread.CurrentUICulture
- };
- //create the new cultures to use
- CultureInfo temporary = new CultureInfo(culture);
- Thread.CurrentThread.CurrentCulture = temporary;
- Thread.CurrentThread.CurrentUICulture = temporary;
- //perform the work
- try { work(); }
- //and make sure to revert the culture
- finally {
- Thread.CurrentThread.CurrentCulture = original.culture;
- Thread.CurrentThread.CurrentCulture = original.uiCulture;
- }
- }
- //grabs the culture string from a type
- private static string _GetCultureString(Culture.Type type) {
- switch (type) {
- case Type.German: return "de-DE";
- case Type.Spanish: return "es-ES";
- //add more cultures as needed
- default: return "en-EN";
- }
- }
- }
Add Comment
Please, Sign In to add comment