C# Get Current Exchange Rate from XE

2019-06-09 08:02发布

问题:


I need to display current exchange rates on my application.
Is it possible to retrieve the exchange rate from http://www.xe.com (XE Converter)
Here what I tried:

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
        {
            string Output = "";
             string fromCurrency1 = comboBox1.Text;
             string toCurrency1 = comboBox2.Text;
             decimal amount1 = Convert.ToDecimal(textBox1.Text);

            // For other currency symbols see http://finance.yahoo.com/currency-converter/
            // Construct URL to query the Yahoo! Finance API

            const string urlPattern = "http://finance.yahoo.com/d/quotes.csv?s={0}{1}=X&f=l1";
            string url = string.Format(urlPattern, fromCurrency1, toCurrency1);

            // Get response as string
            string response = new WebClient().DownloadString(url);

            // Convert string to number
            decimal exchangeRate =
                decimal.Parse(response, System.Globalization.CultureInfo.InvariantCulture);

            // Output the result
            Output = (amount1 * exchangeRate).ToString();
            textBox2.Text = Output;

            return Output;
        }

With this code I am not having the full output... the decimal part is not
showing...

回答1:

Yes XE offers an API but it is paid only. Making an automated tool to extract the data is not allowed. (source)

I tried your code and it is working for me. What do you exactly mean with the decimal part is not showing ?

public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
{
    string url = string.Format(urlPattern, fromCurrency, toCurrency);

    using (var wc = new WebClient())
    {
        var response = wc.DownloadString(url);
        decimal exchangeRate = decimal.Parse(response, CultureInfo.InvariantCulture);

        return (amount * exchangeRate).ToString("N3");
    }
}

TestCode:

Console.WriteLine($"$ 5 = € {CurrencyConversion(5m, "USD", "EUR")}");
Console.WriteLine($"£ 20 = $ {CurrencyConversion(20m, "GBP", "USD")}");

Result:

$ 5 = € 4,661
£ 20 = $ 25,616

EDIT

Get Newtonsoft.Json using NuGet

PM> Install-Package Newtonsoft.Json

Code:

private const string urlPattern = "http://rate-exchange-1.appspot.com/currency?from={0}&to={1}";
    public string CurrencyConversion(decimal amount, string fromCurrency, string toCurrency)
    {
        string url = string.Format(urlPattern, fromCurrency, toCurrency);

        using (var wc = new WebClient())
        {
            var json = wc.DownloadString(url);

            Newtonsoft.Json.Linq.JToken token = Newtonsoft.Json.Linq.JObject.Parse(json);
            decimal exchangeRate = (decimal)token.SelectToken("rate");

            return (amount * exchangeRate).ToString();
        }
    }


标签: c# rate