Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public static class PostalLookup
- {
- public static Postal Find(string countryCode, string postalCode)
- {
- // remove letters from postal code
- postalCode = Regex.Replace(postalCode, "[^0-9]", "");
- if (string.IsNullOrEmpty(postalCode) || postalCode.Length != 4)
- return null;
- if (string.IsNullOrEmpty(countryCode))
- return null;
- // create the web request to the GeoNames interface
- const string geoNamesUrl = "http://ws.geonames.org/postalCodeLookupJSON?postalcode={0}&country={1}";
- WebRequest geoNamesRequest = WebRequest.Create(String.Format(geoNamesUrl, postalCode, countryCode));
- // make the call
- WebResponse geoNamesResponse = geoNamesRequest.GetResponse();
- // grab the response stream
- var geoNamesReader = new StreamReader(geoNamesResponse.GetResponseStream());
- // put the whole response in a string
- string geoNamesContent = geoNamesReader.ReadToEnd();
- try
- {
- JObject o = JObject.Parse(geoNamesContent);
- var postal = new Postal
- {
- Code = (string)o["postalcodes"][0]["postalcode"],
- PlaceName = (string)o["postalcodes"][0]["placeName"],
- County = (string)o["postalcodes"][0]["adminName1"]
- };
- return postal;
- }
- catch
- {
- return null;
- }
- }
- }
- public class Postal
- {
- public string Code { get; set; }
- public string PlaceName { get; set; }
- public string County { get; set; }
- }
Advertisement
Add Comment
Please, Sign In to add comment