2012-09-14 13 views
2

當我使用webclient時,如何在OpenReadCompletedEvent中獲取URL。當我使用webclient時,如何在OpenReadCompletedEvent中獲取URL

WebClient webClient = new WebClient(); 
webClient.OpenReadAsync(url);  // in event method I want get this url  
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(CardInfoDown_Completed); 


private void CardInfoDown_Completed(object sender, OpenReadCompletedEventArgs e) 
    { 
     if (e.Error == null) 
     {   
      using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result)) 
      { 
       // I want get the url here, 
       // How to do this? 
       string strStream = reader.ReadToEnd();    
      } 
     }   
    } 

謝謝!

+1

爲什麼不把網址保持爲全球?並在事件中訪問它? –

回答

4
WebClient webClient = new WebClient(); 
    webClient.BaseAddress = "http://hhh.com"; 
    webClient.OpenReadAsync(new Uri("http://hhh.com"));  // in event method I want get this url  
    webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(CardInfoDown_Completed); 

和:

private void CardInfoDown_Completed(object sender, OpenReadCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result)) 
     { 
      // I want get the url here, 
      // How to do this? 
      var client = sender as WebClient; 
      if (client != null) 
      { 
       var url = client.BaseAddress; //returns hhh.com 
      } 
      string strStream = reader.ReadToEnd(); 
     } 
    } 
+0

我得到的baseaddress爲null在完成的事件..你可以猜測爲什麼? – Mani

1

安東西濟科夫的解決方案是好的,但如果URL是絕對只會工作(如http://hhh.com)。如果使用相對URL,.NET將自動將基地址與相對URL合併(因此可能導致無效URL)。

傳送價值給OpenReadCompleted事件處理程序,你應該利用這個OpenRead過載提供自定義令牌(在這種情況下,您的網址):http://msdn.microsoft.com/en-us/library/ms144212(v=vs.95).aspx

WebClient webClient = new WebClient(); 
webClient.OpenReadAsync(new Uri("http://hhh.com"), "http://hhh.com"); 
webClient.OpenReadCompleted += new OpenReadCompletedEventHandler(CardInfoDown_Completed); 

然後檢索值:

private void CardInfoDown_Completed(object sender, OpenReadCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Result)) 
     { 
      var url = (string)e.UserState; 
      string strStream = reader.ReadToEnd(); 
     } 
    } 
} 
+0

是的,我忘了UserState,謝謝! –

0

對我來說,甚至從上面的簡單變化工作正常

private void CardInfoDown_Completed(object sender, DownloadStringCompletedEventArgs e) 
    { 
     string url; 

     if (e.Error == null) 
     { 
      url = (string)e.UserState; 
     } 
     // ... 
    } 
+0

嗯,我使用了DownloadStringCompletedEventArgs,但實際上它可能與前面的示例具有相同的組成部分。 – juhariis

相關問題