views:

45

answers:

1

I'm creating a method to convert an enum to a friendly string. The friendly names are stored in a resource file and are subject to globalization. So I created two resource file: Enums.resx and Enums.pt-BR.resx whose keys are the name of the enum followed ny it's value (i.e DeliveryStatus_WaitingForPayment).

This is the got I'm using to load the resource and get the corresponding friendly name for the enum:

public static string EnumToString<T>(object obj)
{
      string key = String.Empty;

      Type type = typeof(T);

      key += type.Name + "_" + obj.ToString();

      Assembly assembly = Assembly.Load("EnumResources");

      string[] resourceNames = assembly.GetManifestResourceNames();

      ResourceManager = null;

      for(int i = 0; i < resourceNames.Length; i++)
      { 
           if(resourceNames[i].Contains("Enums.resources"))
           {
                rm = new ResourceManager(resourceNames[i], Assembly.GetExecutingAssembly());

                Stream resStream = assembly.GetManifestResourceStream(resourceNames[i]);

                ResourceReader reader = new ResourceReader(resStream);

                IDictionaryEnumerator dict = reader.GetEnumerator();

                while (dict.MoveNext())
                {
                     string keyToCompare = dict.Key.ToString();

                     if (keyToCompare == key)
                         return dict.Value.ToString();
                }
           }

           return obj.ToString();
      }

}

This method works almost perfectly except that it ignores the CurrentUICulture and aways returns the values from the default resource, that is, even when I'm using pt-BR as my CurrentUICulture it will load the value from Enum.resx and not Enum.pt-BR.resx.

What am I doing wrong?

A: 

As it turns out I was taking the wrong approach to read the resource file. Not only I didn't need to work my way through a stream it was preventing me from getting the result based on the CurrentUICulture.

The solution is much easier than that of my first attempt:

public static string EnumToString<T>(object obj)
{
      string key = String.Empty;

      Type type = typeof(T);

      key += type.Name + "_" + obj.ToString();

      Assembly assembly = Assembly.Load("EnumResources");

      string[] resourceNames = assembly.GetManifestResourceNames();

      ResourceManager = null;

      for(int i = 0; i < resourceNames.Length; i++)
      { 
           if(resourceNames[i].Contains("Enums.resources"))
           {
                //The substring is necessary cause the ResourceManager is already expecting the '.resurces'
                rm = new ResourceManager(resourceNames[i].Substring(0, resourceNames[i].Length - 10), assembly);

                return rm.GetString(key);
           }

           return obj.ToString();
      }

}

I hope this helps anyone trying something similar in the future!

Raphael