2015-08-14 134 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

它的工作!谢谢......如果我可能问,为什么我不喜欢这种方法? –