API for currency exchange rate

Peter_1985 2,546 Reputation points
2022-03-24T09:15:11.363+00:00

Hi,
How about the way to directly retrieve currency exchange rate automatically?

ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,303 questions
ASP.NET API
ASP.NET API
ASP.NET: A set of technologies in the .NET Framework for building web applications and XML web services.API: A software intermediary that allows two applications to interact with each other.
303 questions
{count} votes

1 answer

Sort by: Most helpful
  1. Karen Payne MVP 35,196 Reputation points
    2022-03-24T11:17:12.747+00:00

    Try the following

    public class ExchangeOperations  
    {  
        public static readonly Dictionary<string, decimal> ExchangeRateToEuro = new();  
        public static List<string> FromCurrency = new ();  
        public static List<string> ToCurrency = new ();  
      
        public static void LoadRates()  
        {  
      
            XmlDocument xmlDoc = new XmlDocument();  
            xmlDoc.Load("http://www.ecb.int/stats/eurofxref/eurofxref-daily.xml");  
              
            foreach (XmlNode node in xmlDoc.DocumentElement.ChildNodes[2].ChildNodes[0].ChildNodes)  
            {  
                ExchangeRateToEuro.Add(node.Attributes["currency"].Value, decimal.Parse(node.Attributes["rate"].Value));  
                FromCurrency.Add(node.Attributes["currency"].Value);  
                ToCurrency.Add(node.Attributes["currency"].Value);  
            }  
        }  
    }  
    

    Simple example

    ExchangeOperations.LoadRates();  
      
    decimal amount = 4;  
    decimal conversionNum = (amount / ExchangeOperations.ExchangeRateToEuro["USD"]) *   
                            ExchangeOperations.ExchangeRateToEuro["GBP"];  
      
    Debug.WriteLine(conversionNum.ToString("0.00"));  
    

    This was originally done for VB.NET and converted to C#

    Original code
    https://learn.microsoft.com/en-us/answers/questions/451297/read-currency-rate-details-available-from-web.html