Monday, February 17, 2014

Reading resx programmatically and avoid compiling it with the code

Usually I would be against having a Resources.resx file in production code. It would be better to compile it or put the resources in a database. However, if you need to read the contents in a web project, you could do something like this (from

string resxFile = HttpContext.Current.Server.MapPath(@"/CarResources.resx");
      List<Automobile> autos = new List<Automobile>();
      SortedList headers = new SortedList();

      using (ResXResourceReader resxReader = new ResXResourceReader(resxFile))
         foreach (DictionaryEntry entry in resxReader) {
            if (((string) entry.Key).StartsWith("EarlyAuto"))
               autos.Add((Automobile) entry.Value); 
            else if (((string) entry.Key).StartsWith("Header")) 
               headers.Add((string) entry.Key, (string) entry.Value);      

No comments: