Wednesday, February 3, 2010

Getting Foreign Exchange Currency with C#

Since our online payment service PayEasy works with 24 countries for direct bank debit, we have to perform currency conversion as necessary. For the longest time, I have been using the free currency converter Web Service at webservicex.com -- com.webservicex.www.CurrencyConvertor().

But lately, I don't find it very reliable. I would often get time-outs or errors. Also, I'm not really sure as to where it gets its exchange rates. For manual currency conversion, I prefer to use the service of XE (http://www.xe.com/). However, XE does not provide an API for getting rates. So I decided to just implement my own API by retrieving the output of XE.com and parsing it.

Luckily, its fairly simple as they display the rate right at the page's title bar. So its a simple matter of crafting the necessary HTTP GET request given the source and destination currency. Then read the page header of the response and extract the rate from the title.

Below is a snippet of my C# code:

string xeString = String.Format("http://www.xe.com/ucc/convert.cgi?Amount=1&From={0}&To={1}", srcCurrency, dstCurrency);

System.Net.WebRequest wreq = System.Net.WebRequest.Create(new Uri(xeString));
System.Net.WebResponse wresp = wreq.GetResponse();
Stream respstr = wresp.GetResponseStream();


int read = respstr.Read(buf, 0, BUFFER_SIZE);
result = Encoding.ASCII.GetString(buf, 0, read);

At this point, the string result already contains the title which can look something like
XE.com: USD to EUR rate: 1.00 USD = 0.716372 EUR. As can be clearly seen, its a simple matter of parsing the title in order to get the rate.