2012-07-08 113 views
0

我的方法看起来像这样。 (Grabbed from here)C#中的参数超出范围异常错误#

private void inetConvert() { 
    byte[] buf = new byte[1024]; 
    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)); 
    System.Net.WebResponse wresp = wreq.GetResponse(); 
    Stream respstr = wresp.GetResponseStream(); 
    int read = respstr.Read(buf, 0, 10240); // Error 
    result = Encoding.ASCII.GetString(buf, 0, read); 
    curRateLbl.Text= result; 
} 

的问题是,当应用程序执行这个应用程序挂约4-5秒

enter image description here

我错过之后得到这个屏幕?

+0

如果你有[我的建议,并使用'WebClient'(http://stackoverflow.com/questions/11384950/get-currency-rate-in-c-sharp#comment15006099_11384950),你止跌”不需要担心缓冲区大小。 – Adam 2012-07-08 18:48:01

回答

12

缓冲区的大小是1024,但是你告诉Read它可以将10240(十倍大小)字节放入缓冲区。如文档所述,它会抛出,因为

偏移量和计数的总和大于缓冲区长度。

1

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

没有。阅读源博客。它们是2个不同的变量int read = respstr.Read(buf,0,BUFFER_SIZE); – heron 2012-07-08 18:07:09

+0

什么是'buf'和什么是'size'?他们需要多少钱? – heron 2012-07-08 18:07:46

+0

更正...但重点是相同的。使用CONST。 – 2012-07-08 18:10:02