Sunday, March 13, 2016

C# Currency Converter using Google API

Currency conversion in C# using Google API

  • There are so many ways to convert amount from one currency to another currency like using google finance converter, Yahoo finance and rate-exchange.
  • In this post i will show conversion using Google Finance Converter.
  • In below code, I create one WebRequest for Google Finance Converter which will return result of arguments which are attached with it.
  • Get the response of WebRequest in form of Stream and stored it in streamReader (which is the object of StreamReader Class).
  • By using, Regex fetched converted amount with desired currency code and stored this result into a string variable and again using Regex fetched only decimal part from generated string.
Hope this post will help you to get the exact result that you want.
public string CurrencyConvert(decimal amount, string fromCurrency, string toCurrency)
      decimal currency = 0;
      string convertedAmount = "0";
          string url = string.Format("{2}&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount);
          WebRequest request = WebRequest.Create(url);
          StreamReader streamReader = new StreamReader(request.GetResponse().GetResponseStream(), System.Text.Encoding.ASCII);
          string result = Regex.Matches(streamReader.ReadToEnd(), "([^<]+)")[0].Groups[1].Value;
          string rs = new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*").Match(result).Groups[1].Value;
          if (decimal.TryParse((new Regex(@"^\D*?((-?(\d+(\.\d+)?))|(-?\.\d+)).*").Match(result).Groups[1].Value), out currency))
              convertedAmount = currency.ToString("0.00");
      catch (Exception ex)
          throw ex;
      return convertedAmount;