http://msdn.microsoft.com/fr-fr/library/system.io.stream.read.aspx
BUF是一個字節[]數組,其中,一旦方法返回,包含剛讀取數據。 BUFFER_SIZE是您想要讀取的數據的大小。如果你想讀一個字節,BUFFER_SIZE = 1。如果你想讀取一千字節的數據,BUFFER_SIZE = 1024等。注意,如果你要求一個太大的緩衝區(例如當數據是1KB時請求1MB),那麼它並不重要。它會讀取一個KB,然後返回。
你最終的字符串應該是這樣的,除非XE.com決定改變它:
XE.com:美元對歐元匯率:1.00美元= 0.716372歐元
您可以使用String方法脫光東西你並不需要:整個第一部分
(XE.com: USD to EUR rate:)
可以通過只是建立一個字符串,您的數據很容易地刪除:
(string header = "XE.com: {0} to {1} rate:", currency1, currency2)
,然後調用String.Replace(header, '')
。從那裏,你可以在「=」號呼叫String.Split('=')
,分裂,再從分裂串取出貨幣部分(再次,String.Replace()
),最後調用Double.TryParse()
注:codesparkle的方法是比較容易的方式,因爲你基本上跳過第1步。但是XE.com沒有提供API:你不能保證返回的字符串是有效的,或者將來有一天不會改變。
OK,這裏的一些代碼:
private double GetConvertedCurrencyValue(string inputCurrency, string outputCurrency, double value)
{
string request = String.Format(http://www.xe.com/ucc/convert.cgi?Amount={0}&From={1}&To={2}", value, inputCurrency, outputCurrency);
System.Net.WebClient wc = new System.Net.WebClient();
string apiResponse = wc.DownloadString(request); // This is a blocking operation.
wc.Dispose();
/* Formatting */
// Typical response: "XE.com: curr1 to curr2 rate: x curr1 = y curr2"
// The first part, up until "x curr1" is basically a constant
string header = String.Format("XE.com: {0} to {2} rate:" inputCurrency, outputCurrency);
// Removing the header
// The response now looks like this: x curr1 = y curr2
apiResponse = apiResponse.Replace(header, "");
// Let's split the response at '=', to retrieve the right part
string outValue = apiResponse.Split('=')[1];
// Getting rid of the 'curr2' part
outValue = outValue.Replace(outputCurrency, "");
return Double.Parse(outValue, System.Globalization.CultureInfo.InvariantCulture);
}
我建議忘記'WebRequest' /'WebResponse';使用['WebClient.DownloadString'](http://msdn.microsoft.com/en-us/library/fhd1f0sw(v = vs.80).aspx)或['WebClient.DownloadStringAsync'](http:// msdn .microsoft.com/en-us/library/ms144202(v = vs.80))而不是... – Adam 2012-07-08 17:05:26
@codesparkle你能不能在代碼中顯示你的想法? – heron 2012-07-08 17:06:18
只是看看[MSDN上的示例](http://msdn.microsoft.com/en-us/library/fhd1f0sw(v = vs.80)#Y833),它不是火箭科學 – Adam 2012-07-08 17:08:10