Search code examples
wpfdynamiclocalizationresourcedictionary

create resource-file for localization out of txt-file dynamically within the code


my app has to be multilingual, so i created some resource-files which hold the texts e.g.:

texts.resx
texts.en.resx
texts.fr.resx

that works all fine so far.

but some of the texts are generated with an external tool. i end up with a normal text-file (*.txt) which holds the strings like that:

key|language1|language2|language3

so what i need to do is read that file at the start and generate the according resource-files.

what i did so far:

reading the file with a StreamReader and filling lists with the keys and the languages

line = reader.ReadLine();
char[] delimiterChars = { '|' };
string[] parts = line.Split(delimiterChars);
keyList.Add(parts[0]);
language1List.Add(parts[1]);
language2List.Add(parts[2]);

generating the resource-files:

using (ResXResourceWriter resx = new ResXResourceWriter("test.resx"))
{
    for (int i = 0; i < keyList.Count; i++)
    {
        resx.AddResource(keyList[i], language1List[i]);
    }
}
using (ResXResourceWriter resx = new ResXResourceWriter("test.en.resx"))
{
    for (int i = 0; i < keyList.Count; i++)
    {
        resx.AddResource(keyList[i], language2List[i]);
    }
}

getting a string from the resource-file:

using (ResXResourceSet resxSet = new ResXResourceSet("test.resx"))
{
    Text = resxSet.GetString(keyList[0]);
}

that works all fine.

the questions

  1. how do i change the language? if i set the culture, the programm "magically" takes the right resource-file, but not the right generated one. when i change it to ("text.en.resx") it obviously works.
  2. how can i access the strings from the view? during design-time, the resource-files don't exist, so i get an error.

Solution

  • i think i got a solution: generating the resource-files:

    IResourceWriter writer = new ResourceWriter("test.resx");
    for (int i = 0; i < keyList.Count; i++)
    {
        writer.AddResource(keyList[i], language1List[i]);
    }
    IResourceWriter writer = new ResourceWriter("test.en.resx");
    for (int i = 0; i < keyList.Count; i++)
    {
        writer.AddResource(keyList[i], language2List[i]);
    }
    

    this creates *.resources instead of *.resx files. they can be read like that:

    ResourceManager rm = ResourceManager.CreateFileBasedResourceManager("test", location, null);
    Text = rm.GetString("foo");
    

    depending on the set culture, the ResourceManager reads the right file and gets the correct text.