2012-07-08 77 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