2

使用 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();              
            }
        }          
    }

谢谢!

4

3 回答 3

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();
        }
    }
于 2012-09-14T09:55:19.143 回答
1

Anton Sizikov 的解决方案很好,但仅当 URL 是绝对的(如http://hhh.com)时才有效。如果使用相对 URL,.NET 将自动将基地址与相对 URL 合并(因此可能会导致无效的 URL)。

要将值发送到OpenReadCompleted事件处理程序,您应该使用此OpenRead重载来提供自定义令牌(在本例中为您的 URL):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();
        }
    }
}
于 2012-09-14T11:52:34.517 回答
0

对我来说,即使是上述更简单的变化也可以正常工作

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

        if (e.Error == null)
        {
            url  = (string)e.UserState;
        }
       // ...
    }
于 2014-03-30T17:47:46.080 回答