Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying existing resource file programmatically

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 crated from above code. If i use the same code, the existing resource file gets replaced. Please help me modify it without loosing the existing contents.

Best Regards, Ankit

like image 724
Ankit Goel Avatar asked Sep 05 '13 10:09

Ankit Goel


1 Answers

public static void AddOrUpdateResource(string key, string value)
{
    var resx = new List<DictionaryEntry>();
    using (var reader = new ResXResourceReader(resourceFilepath))
    {
        resx = reader.Cast<DictionaryEntry>().ToList();
        var existingResource = resx.Where(r => r.Key.ToString() == key).FirstOrDefault();
        if (existingResource.Key == null && existingResource.Value == null) // NEW!
        {
            resx.Add(new DictionaryEntry() { Key = key, Value = value });
        }
        else // MODIFIED RESOURCE!
        {
            var modifiedResx = new DictionaryEntry() { Key = existingResource.Key, Value = value };
            resx.Remove(existingResource);  // REMOVING RESOURCE!
            resx.Add(modifiedResx);  // AND THEN ADDING RESOURCE!
        }
    }
    using (var writer = new ResXResourceWriter(ResxPathEn))
    {
        resx.ForEach(r =>
        {
            // Again Adding all resource to generate with final items
            writer.AddResource(r.Key.ToString(), r.Value.ToString());
        });
        writer.Generate();
    }
}
like image 75
Elias Hossain Avatar answered Oct 05 '22 12:10

Elias Hossain