当我使用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();
}
}
}
谢谢!
答案 0 :(得分: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();
}
}
答案 1 :(得分:1)
Anton Sizikov的解决方案很好,但只有在URL绝对时才会起作用(如http://hhh.com
)。如果使用相对URL,.NET将自动将基地址与相对URL合并(因此可能导致URL无效)。
要向OpenReadCompleted
事件处理程序发送值,您应该使用此OpenRead
重载来提供自定义令牌(在本例中为您的网址):http://msdn.microsoft.com/en-us/library/ms144212(v=vs.95).aspx < / p>
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();
}
}
}
答案 2 :(得分:0)
对我来说,即使是上述更简单的变化也能正常工作
private void CardInfoDown_Completed(object sender, DownloadStringCompletedEventArgs e)
{
string url;
if (e.Error == null)
{
url = (string)e.UserState;
}
// ...
}