[英]How can I get the URL in OpenReadCompletedEvent when I use webclient
How can I get the URL in OpenReadCompletedEvent when I use webclient. 使用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();
}
}
}
Thank you! 谢谢!
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);
And: 和:
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();
}
}
Anton Sizikov's solution is good, but will only work if the URL is absolute (like http://hhh.com
). 安东·西齐科夫(Anton Sizikov)的解决方案很好,但是仅在URL是绝对的(例如
http://hhh.com
)时才可以使用。 If using a relative URL, .NET will automatically merge the base address with the relative URL (therefore potentially resulting in an invalid URL). 如果使用相对URL,.NET将自动将基本地址与相对URL合并(因此可能导致无效的URL)。
To send a value to the OpenReadCompleted
event handler, you're supposed to use this OpenRead
overload to provide a custom token (in this case, your URL): http://msdn.microsoft.com/en-us/library/ms144212(v=vs.95).aspx 要将值发送到
OpenReadCompleted
事件处理程序,您应该使用此OpenRead
重载来提供自定义标记(在本例中为URL): http : //msdn.microsoft.com/zh-cn/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);
Then to retrieve the value: 然后检索值:
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();
}
}
}
For me even a simpler variation from the above works fine 对我来说,即使是上述方法的更简单的变化也可以
private void CardInfoDown_Completed(object sender, DownloadStringCompletedEventArgs e)
{
string url;
if (e.Error == null)
{
url = (string)e.UserState;
}
// ...
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.