你在最後有一個額外的0。應該是
int read = respstr.Read(buf, 0, 1024); // Error
這就是爲什麼你在你的應用中使用常量,以避免那些胖乎乎的手指錯誤。
private void inetConvert() {
private const BUFFER_SIZE = 1024;
byte[] buf = new byte[BUFFER_SIZE];
string result;
string xeString = String.Format("http://www.xe.com/ucc/convert.cgi?Amount=1&From={0}&To={1}", srcCurrency, dstCurrency);
System.Net.WebRequest wreq = System.Net.WebRequest.Create(new Uri(xeString));
// VERY IMPORTANT TO CLEAN UP RESOURCES FROM ANY OBJECT THAT IMPLEMENTS IDisposable
using(System.Net.WebResponse wresp = wreq.GetResponse())
using(Stream respstr = wresp.GetResponseStream())
{
int read = respstr.Read(buf, 0, BUFFER_SIZE); // Error
result = Encoding.ASCII.GetString(buf, 0, read);
curRateLbl.Text= result;
}
}
另請注意,您沒有正確關閉Stream對象。您可以考慮使用using
語句來幫助管理流中的資源。
但是...這是我將如何做到這一點。
private void inetConvert()
{
string xeString= String.Format("http://www.xe.com/ucc/convert.cgi?Amount=1&From={0}&To={1}", srcCurrency, dstCurrency);
System.Net.WebRequest wreq = System.Net.WebRequest.Create(new Uri(xeString));
// VERY IMPORTANT TO CLEAN UP RESOURCES FROM ANY OBJECT THAT IMPLEMENTS IDisposable
using(System.Net.WebResponse wresp = wreq.GetResponse())
using (Stream stream = response.GetResponseStream())
{
StreamReader reader = new StreamReader(stream, Encoding.UTF8);
curRateLbl.Text = reader.ReadToEnd();
}
}
如果你有[我的建議,並使用'WebClient'(http://stackoverflow.com/questions/11384950/get-currency-rate-in-c-sharp#comment15006099_11384950),你止跌」不需要擔心緩衝區大小。 – Adam 2012-07-08 18:48:01