Get a country code from an address in c#
If you have a partial address, or just a town / city name and you’d like to get the country code (ISO3166) then you can use Google’s geocode API from c# as follows;
The Google API key is not strictly necessary, but it’s recommended, as they will probably throttle use for unauthenticated calls.
public static string GetCountryFromAddress(string address)
{try
{
// API key is recommended, but not required
const string strGoogleApiKey = “….”;
var strUrl = “https://maps.googleapis.com/maps/api/geocode/json?address={0}&key={1}”;
strUrl = string.Format(strUrl, address, strGoogleApiKey);
var wc = new WebClient();
var strJson = wc.DownloadString(strUrl);
var json = JObject.Parse(strJson);
var jResult = json[“results”][0];
var jAddressComponents = jResult[“address_components”];
foreach (var jAddressComponent in jAddressComponents)
{
var jTypes = jAddressComponent[“types”];
if (jTypes.Any(t => t.ToString() == “country”))
{
return jAddressComponent[“short_name”].ToString();
}
}
return null;
}
catch
{
return null;
}
}
PS: This requires the Newtonsoft.Json nuget package
LikeLike