Geoip for .net – IPInfoDb in C#

The following code (C# class) will access the IPInfoDB api with .net/c# code. Visit http://ipinfodb.com for more information about the api and to obtain your own api key.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Web;
using System.Xml;

public class GeoLookup
{
public bool GetGeo(string IP)
{

string key = "YOURKEYHERE"; //replace with your actual key.
string url = "http://api.ipinfodb.com/v3/ip-city/?format=xml&key=" + key + "&ip=";

HttpWebResponse res = null;

try
{
var req = WebRequest.Create(url + IP) as HttpWebRequest;

XmlDocument xob = null;

res = req.GetResponse() as HttpWebResponse;
if (req.HaveResponse == true && res != null)
{
xob = new XmlDocument();
xob.Load(res.GetResponseStream());
}
else return false;

if (xob != null)
{
var x = xob.SelectSingleNode("Response");
if (x != null)
{
StatusCode = x["statusCode"].InnerText;
StatusMessage = x["statusMessage"].InnerText;
IpAddress = x["ipAddress"].InnerText;
CountryCode = x["countryCode"].InnerText;
CountryName = x["countryName"].InnerText;
RegionName = x["regionName"].InnerText;
CityName = x["cityName"].InnerText;
ZipCode = x["zipCode"].InnerText;
Latitude = x["latitude"].InnerText;
Longitude = x["longitude"].InnerText;
TimeZone = x["timeZone"].InnerText;

}
}
else return false;

}
catch { return false; }
finally
{
if (res != null)
{ res.Close(); }
}
return true;

}

//access the following properties after a successful lookup.
public String StatusCode { get; set; }
public String StatusMessage { get; set; }
public String IpAddress { get; set; }
public String CountryCode { get; set; }
public String CountryName { get; set; }
public String RegionName { get; set; }
public String CityName { get; set; }
public String ZipCode { get; set; }
public String Latitude { get; set; }
public String Longitude { get; set; }
public String TimeZone { get; set; }
}