Identifying originating country of an IP address I have a small assignment to read IP addresses and from a bunch of external text files identify which country the IP address comes from. I opted to use XmlReader and read the ranges from an XML file but unfortunately the performance has been quite abysmal (an average search time of around 7000 milliseconds).

Obviously serializing the ranges isn't an option as we're talking about 142,222 entries. Is there anything I can do to optimize my method or is there a quicker way to search this, without resorting to SQL?

class IPRangeRepository : IDisposable
    {
        public IPRangeRepository(string fileName)
        {
            this.fileName = fileName;
            xmlReader = XmlReader.Create(fileName);
        }

        private XmlReader xmlReader;
        private string fileName;

        public string GetIPCountry(IPAddress adress)
        {
            while (xmlReader.Read())
            {
                // Ok instantiate object and then do comparison... 
                if (xmlReader.Name == "IPRange") { 
                var ipRange = IPRange.TryParse(xmlReader["Value"]);
                if (ipRange.IsIPAddressInRange(adress)) return xmlReader["Country"];
                }
            }

            //Return empty string if we don't find anything
            return string.Empty;
        }

        public void Dispose()
        {
            xmlReader.Dispose();
        }
    }
the only issues that I see with this code so far is formatting.


class IPRangeRepository : IDisposable
    {
        public IPRangeRepository(string fileName)
        {
            this.fileName = fileName;
            xmlReader = XmlReader.Create(fileName);
        }



This indentation is not standard, it should look like this

class IPRangeRepository : IDisposable
{
    public IPRangeRepository(string fileName)
    {
        this.fileName = fileName;
        xmlReader = XmlReader.Create(fileName);
    }


and your if statements inside the while loop are not easy to read.


        while (xmlReader.Read())
        {
            // Ok instantiate object and then do comparison... 
            if (xmlReader.Name == "IPRange") { 
            var ipRange = IPRange.TryParse(xmlReader["Value"]);
            if (ipRange.IsIPAddressInRange(adress)) return xmlReader["Country"];
            }
        }



this is how I prefer to write this code

while (xmlReader.Read())
{
    // Ok instantiate object and then do comparison... 
    if (xmlReader.Name == "IPRange") { 
        var ipRange = IPRange.TryParse(xmlReader["Value"]);
        if (ipRange.IsIPAddressInRange(adress)) 
        {
            return xmlReader["Country"];
        }
    }
}


the return is a little too complex for something that I would one line, and most of the time if I can one line something it's going to look better as a ternary statement, this isn't one of those instances.

Always indent code inside of any block.