Tuesday, May 18, 2010

Easy fix for duplicate keys in a resource file (resx)

Today I was cleaning up some RESX files by doing some renaming (to conform to a naming conventions) and ran into the classic duplicate mnemonic problem that arise. With hundreds or thousands of mnemonic in a resource file this can become very time consuming. RESX files are not case sensitive which adds a little joy to the process…

 

I tossed together a utility that eliminates all of these duplicates and also sorts the mnemonics in the physical RESX file. This made reviewing a lot easier – so here’s the code in case you need it, just provide the folder holding the RESX files and you are done.

 

using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

class Program
{
    static void Main(string[] args)
    {
        if (args.Length < 1)
            return;
        DirectoryInfo di = new DirectoryInfo(args[0]);
        foreach (FileInfo fi in di.GetFiles("*.resx"))
        {
            XmlDocument dom = new XmlDocument();
            dom.Load(fi.FullName);
            var list = new SortedList<string, XmlNode>();

            foreach (XmlNode node in dom.SelectNodes("//data[@name]"))
            {
                var key = node.Attributes["name"].Value.ToLower();
                if (!list.ContainsKey(key))
                    list.Add(key, node);
                node.ParentNode.RemoveChild(node);
            }
            foreach (string key in list.Keys)
            {
                dom.DocumentElement.AppendChild(list[key]);
            }
            dom.Save(fi.FullName);
        }
    }
}

2 comments: