Skip to content

Instantly share code, notes, and snippets.

@tomcurran
Created May 13, 2020 13:14
Show Gist options
  • Save tomcurran/ac71a62365f188b0aed1fd14b9293c88 to your computer and use it in GitHub Desktop.
Save tomcurran/ac71a62365f188b0aed1fd14b9293c88 to your computer and use it in GitHub Desktop.
Resx entry duplicates & order
uti id title platforms
com.xamarin.workbook
67ee3be8-703f-4566-9b19-227768fb9dc5
Untitled
Console
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;

List<string> GetDuplicates(string[] args)
{
    var duplicates = new HashSet<string>();

    if (args.Length < 1)
    {
        return duplicates.ToList();
    }

    DirectoryInfo di = new DirectoryInfo(args[0]);
    foreach (FileInfo fi in di.GetFiles("*.resx"))
    {
        XmlDocument dom = new XmlDocument();
        dom.Load(fi.FullName);
        var keySet = new HashSet<string>();

        foreach (XmlNode node in dom.SelectNodes("//data[@name]"))
        {
            var key = node.Attributes["name"].Value.ToLower();
            if (keySet.Contains(key))
            {
                duplicates.Add(key);
            }
            keySet.Add(key);
        }
    }
    return duplicates.ToList();
}

void OrderResxKeys(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);
    }
}

var files = new string[] { "directory_with_resx_files_here" };
var dups = GetDuplicates(files);
if (dups.Any())
{
    Console.WriteLine($"Duplicate keys found: {string.Join(", ", dups)}");
}
else
{
    Console.WriteLine("No duplicate keys found");
    Console.WriteLine("Ordering keys in file...");
    OrderResxKeys(files);
    Console.WriteLine("Finished");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment