2015-08-14 120 views
1

我在過去幾年使用過這段代碼,但谷歌似乎已經改變了他們的一些鏈接。出於某種原因,我收到此錯誤消息:谷歌貨幣轉換器

「輸入字符串格式不正確。」

在下面一行:

decimal rate = System.Convert.ToDecimal(match.Groups[1].Value); 

我的代碼:

try 
{ 
    WebClient web = new WebClient(); 
    string url = string.Format("https://www.google.com/finance/converter?a={2}&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount); 

    string response = web.DownloadString(url); 

    Regex regex = new Regex("rhs: \\\"(\\d*.\\d*)"); 
    Match match = regex.Match(response); 
    decimal rate = System.Convert.ToDecimal(match.Groups[1].Value); 

    return rate; 
} 
catch 
{ 
    return 0; 
} 

回答

7

你可能不喜歡這種方法,但它獲得的完成任務。

WebClient web = new WebClient(); 
string url = string.Format("https://www.google.com/finance/converter?a={2}&from={0}&to={1}", fromCurrency.ToUpper(), toCurrency.ToUpper(), amount); 

string response = web.DownloadString(url); 

var split = response.Split((new string[] { "<span class=bld>"}),StringSplitOptions.None); 
var value = split[1].Split(' ')[0]; 
decimal rate = decimal.Parse(value,CultureInfo.InvariantCulture); 
+0

輸入字符串的不正確的格式。 - 同樣的錯誤:/ –

+0

@MarkFenech檢查我編輯的答案 –

+0

它的工作!謝謝......如果我可能問,爲什麼我不喜歡這種方法? –