8

I am using the following code to generate resource file programmatically.

ResXResourceWriter resxWtr = new ResXResourceWriter(@"C:\CarResources.resx");
resxWtr.AddResource("Title", "Classic American Cars");
resxWtr.Generate();
resxWtr.Close();

Now, I want to modify the resource file created from the above code. If I use the same code, the existing resource file gets replaced. How to modify it without losing the existing contents?

Dharman
  • 30,962
  • 25
  • 85
  • 135
Ankit Goel
  • 353
  • 1
  • 4
  • 13

2 Answers2

1

I had the same problem this resolve it:

This will append to your existing .resx file

 var reader = new ResXResourceReader(@"C:\CarResources.resx");//same fileName
 var node = reader.GetEnumerator();
 var writer = new ResXResourceWriter(@"C:\CarResources.resx");//same fileName(not new)
 while (node.MoveNext())
         {
     writer.AddResource(node.Key.ToString(), node.Value.ToString());
       }
  var newNode = new ResXDataNode("Title", "Classic American Cars");
  writer.AddResource(newNode);
  writer.Generate();
  writer.Close();
Vladimir Potapov
  • 2,347
  • 7
  • 44
  • 71
0

Here is a function that would help you modify the resource file.

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();

}

Reference link here

Community
  • 1
  • 1
Harsh
  • 3,683
  • 2
  • 25
  • 41
  • 1
    I don't want to re-write existing resource file, i just want to append new resources to it. Is there any other way? – Ankit Goel Sep 10 '13 at 04:15