I have a .resx
file that contains name-value pairs (both strings). Now I want to modify the values in certain name-value pairs programmatically using C#. How can I achieve that?
There's a whole namespace for resource management: System.Resources. Check out the ResourceManager class, as well as ResXResourceReader and ResXResourceWriter.
http://msdn.microsoft.com/en-us/library/system.resources.aspx
I managed to lay my hands on a very old debug method that I used to use at one point when I was testing some resource related stuff. This should do the trick for you.
public static void UpdateResourceFile(Hashtable data, String path)
{
Hashtable resourceEntries = new Hashtable();
//Get existing resources
ResXResourceReader reader = new ResXResourceReader(path);
if (reader != null)
{
IDictionaryEnumerator id = reader.GetEnumerator();
foreach (DictionaryEntry d in reader)
{
if (d.Value == null)
resourceEntries.Add(d.Key.ToString(), "");
else
resourceEntries.Add(d.Key.ToString(), d.Value.ToString());
}
reader.Close();
}
//Modify resources here...
foreach (String key in data.Keys)
{
if (!resourceEntries.ContainsKey(key))
{
String value = data[key].ToString();
if (value == null) value = "";
resourceEntries.Add(key, value);
}
}
//Write the combined resource file
ResXResourceWriter resourceWriter = new ResXResourceWriter(path);
foreach (String key in resourceEntries.Keys)
{
resourceWriter.AddResource(key, resourceEntries[key]);
}
resourceWriter.Generate();
resourceWriter.Close();
}