最后你有一个额外的 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();
}
}