Click here to Skip to main content
15,304,433 members
Articles / Web Development / ASP.NET
Posted 7 Mar 2007


81 bookmarked

Simple Class to get Currency Exchange Rates

Rate me:
Please Sign up or sign in to vote.
4.74/5 (23 votes)
12 Mar 2007CPOL5 min read
Explains how to get the latest currency exchange rates from the Internet.


Many years, especially during international trips, I have used the Yahoo! Finance portal to get fresh foreign exchange rates for my expense reports. I found this site quite useful, especially because the information is free, even though a little bit delayed, but good enough for such goals. Unfortunately, the Yahoo! site doesn't have a version formatted to fit the small screens of mobile devices. That's why I decided to create .NET components that are reusable in WinForms, ASP.NET, and the Compact Framework to cover all my needs. Parsing HTML code is not a trivial task because it doesn't have a strong formatting as XML does. Again, fortunately, Yahoo! duplicates results as a comma-delimited file which is more easy to parse. So, let's look at the code closely.

Walk through the classes

Class diagram:

Image 1

There are two classes - CurrencyConverter and CurrencyList, and a structure CurrencyData. All of them are packed into the Zayko.Finance namespace.

CurrencyData structure

This structure represents a pair of currency codes and data coming from the Web Service:

  • BaseCode (string): get/set three-characters of the base currency code, for example: USD for United States Dollar, EUR for Euro etc.
  • TargetCode (string): get/set the target currency code, by the same rules as BaseCode.
  • Rate (double): last trade price of Base Currency, specified in the BaseCode property, calculated in currency units, specified in the TargetCode property.
  • Max and Min (double): they look like Ask and Bid, but values are different between the HTML version on the site and the comma-delimited file I mentioned above; unfortunately, there is no detailed explanation, that's why I named them "Min" and "Max" to avoid confusion with the real "Bid" and "Ask" values.
  • TradeDate (System.DateTime): last trade Date/Time.

This structure has one constructor:

public CurrencyData(string baseCode, string targetCode)

to create a new structure and set the currency codes.

CurrencyConverter class

This is the main class which accesses the Yahoo! service and gets the data through several overloads of the GetCurrencyData method:

public CurrencyData GetCurrencyData(string source, string target)

This is the simplest method: just supply the currency codes and get the result in the returned CurrencyData structure. For example:

using Zayko.Finance;
CurrencyData cd = myCurrencyConverter.GetCurrencyData("USD", "EUR");
// Convert US Dollars to Euros

This version gets the currency pair in the supplied CurrencyData and packs the results back into there:

public void GetCurrencyData(ref CurrencyData data)

Gets the currency pair in the CurrencyData structure and sets the data properties (Rate, Min/Max, TradeDate) by the given results. Example:

using Zayko.Finance;
CurrencyData cd = new CurrencyData("EUR", "RUB");
// Creates new structure and set Base currency
// to Euro and Target to Russian Ruble

    myCurrencyConverter.GetCurrencyData(ref cd);
    // cd.Rate contains last price of Euro in Russian Rubles
    // Catch an exception

This method is useful to get data for more than one currency pair at the same time:

public void GetCurrencyData(ref IList<CurrencyData> listData);


using Zayko.Finance;
IList<CurrencyData> currencyList = new List<CurrencyData>();
currencyList.Add(new CurrencyData("USD", "EUR"));
currencyList.Add(new CurrencyData("EUR", "RUR"));
    myCurrencyConverter.GetCurrencyData(ref currencyList);
    foreach(CurrencyData cd in currencyList)
        // listing the data
    // Catch an exception

But before calling these functions, don't forget to set some important properties:

  • System.Net.WebProxy Proxy: represents a proxy server, if any; just skip this step if there is no proxy in your network.
  • bool AdjustToLocalTime: basically, CurrencyData.TradeDate is US Eastern Time (GMT-05:00).
  • Set this property to true if you want to adjust this time to your local automatically.

  • int Timeout and ReadWriteTimeout: same meaning as HttpWebRequst: namely, the time-out value for the GetResponse and GetRequestStream methods for Timeout and the time-out when writing to or reading from a stream for ReadWriteTimeout in milliseconds. Both defaulted to 30 seconds (30000 milliseconds).

CurrencyList class

This class contains only static methods, so doesn't need to be created manually before using it. Use this class to get all the supported currencies: get the three-characters codes from the static read only property Codes: public static ReadOnlyCollection Codes and their names from public static ReadOnlyCollection Descriptions.

Also, it is possible to get the exact code and/or description by its position:

  • public static string GetCode(int index): return a currency code, for example "USD".
  • public static string GetDescription(int index): return a currency description (name), for example "U.S. Dollar".

and opposite functions:

  • public static int GetCodeIndex(string code)
  • public static int GetDescriptionIndex(string description)

Since both codes and descriptions are unique, it's possible to get a currency code by its description and vice versa:

  • public static string GetCode(string description)
  • public static string GetDescription(string code)

Using the code

Finally, a couple of words about using the source code.

Probably the best way to show all the supported currencies either in a WinForms app or an ASP.NET app is ListBox or ComboBox objects. As I said above, this list could be taken from the static CurrencyList class. This task could be done in two different ways:

// 1. Simply fill Combo or ListBox Items property...
string[] currencyDescriptions = new string[CurrencyList.Count];
CurrencyList.Descriptions.CopyTo(currencyDescriptions, 0);

// 2. Assign currencies one-by-one and set Value properties
//    to corresponded codes at the same time (useful in ASP.NET):
for(int i = 0; i < CurrencyList.Count; i++)
    DropDownListCurrency.Items[i].Value = CurrencyList.Codes[i];

// then simply use them in CurrencyData GetCurrencyData method:
CurrencyConverter cc = new CurrencyConverter();
CurrencyData cd = cc.GetCurrencyData(DropDownListFrom.SelectedValue, 

Don't forget to set the CurrencyData.AdjustToLocalTime property to true if you want to make adjustments automatically. If your network is behind a proxy, don't forget to create and assign a proxy object before you call CurrencyData.GetCurrencyData(...):

    cc.Proxy = new System.Net.WebProxy(proxyAddress, proxyPort);

Because the CurrencyConverter class has several versions of the GetCurrencyData method, and GetCurrencyData(ref IList<CurrencyData>) is one of them, you can pass more than one CurrencyData structure and get data for several currency pairs at the same time. Although this method has no restrictions on the number of currencies you can pass, please remember that some old network routers have a limitation on URL length and can trim everything to below 256 characters.

Here is the demo app screenshot (source code is included with this article):

Image 2

Important notes

As a developer, I don't impose any restrictions on using this code, but please remember that Yahoo! services could be under different types of licensing and commercial use could be restricted. So please follow Yahoo! instructions.

Although I said at the beginning that I created these classes to fit to any .NET target, I didn't test this code on the Compact Framework at all, but I promise to return to this article in a couple of weeks and hope will get your opinions during this time to make this code more useful.




  • March 7, 2007 - Initial release.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

Vitaly Zayko
Software Developer (Senior)
Russian Federation Russian Federation
More than 15 years in the industry.
Delphi, C# (Win/WebForms), MS SQL

Comments and Discussions

Questionwhat is the password ? Pin
Member 111280872-Oct-17 7:33
MemberMember 111280872-Oct-17 7:33 
Questionthz u Pin
naymyohaen23-Feb-16 1:43
Membernaymyohaen23-Feb-16 1:43 
AnswerRe: thz u Pin
Member 1207622529-Nov-16 20:51
MemberMember 1207622529-Nov-16 20:51 
GeneralПолезный пример Pin
Sergey Lapp11-Oct-14 21:39
MemberSergey Lapp11-Oct-14 21:39 
QuestionNice useful class. Pin
pkfox13-Jan-14 23:20
professionalpkfox13-Jan-14 23:20 
QuestionClass Pin
Rachal Chow21-Jul-13 2:32
MemberRachal Chow21-Jul-13 2:32 
QuestionHistorical Rates Pin
Henrique Clausing21-May-13 1:55
MemberHenrique Clausing21-May-13 1:55 
Questionneed code for Pin
Mian Abid Ali16-Feb-13 2:03
MemberMian Abid Ali16-Feb-13 2:03 
QuestionError:The remote server returned an error: (404) Not Found. Pin
Chirag Lukhi25-Jan-12 1:30
MemberChirag Lukhi25-Jan-12 1:30 
QuestionHow to compile in vs 2010? Pin
atif_sh2-Jan-12 3:18
Memberatif_sh2-Jan-12 3:18 
GeneralMy vote of 5 Pin
atif_sh2-Jan-12 3:16
Memberatif_sh2-Jan-12 3:16 
GeneralMy vote of 5 Pin
hakimsameh22-Dec-11 4:45
Memberhakimsameh22-Dec-11 4:45 
QuestionUsing Zayko with CultureInfo class Pin
~Pete27-Nov-11 4:22
Member~Pete27-Nov-11 4:22 
AnswerAmazing Pin
WossiBock663-Nov-11 1:31
MemberWossiBock663-Nov-11 1:31 
QuestionHow to read the .chm file Pin
Spokane-dude3-Oct-11 10:40
MemberSpokane-dude3-Oct-11 10:40 
Questionpassword Pin
aaashivabalaji5-Aug-11 3:21
Memberaaashivabalaji5-Aug-11 3:21 
Generalgrand merci) Pin
sherpc11-Feb-11 12:29
Membersherpc11-Feb-11 12:29 
GeneralPassword Pin
Amit Rajani24-Nov-10 20:09
MemberAmit Rajani24-Nov-10 20:09 
Questionwhat is the password Pin
siren993315-Nov-10 21:45
Membersiren993315-Nov-10 21:45 
GeneralPassword Pin
elaiz26-Oct-10 5:08
Memberelaiz26-Oct-10 5:08 
GeneralThanks Pin
Danie de Kock7-Oct-10 22:03
MemberDanie de Kock7-Oct-10 22:03 
Generalpassword Pin
asafbr10-May-10 23:24
Memberasafbr10-May-10 23:24 
QuestionCan i have same example writing by delphi Pin
Rami Khoury9-Jan-10 12:37
MemberRami Khoury9-Jan-10 12:37 
Generalthank you Pin
Rami Khoury9-Jan-10 12:00
MemberRami Khoury9-Jan-10 12:00 
GeneralThank u Pin
essam_ag28-Dec-09 20:16
Memberessam_ag28-Dec-09 20:16 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.