从DownloadStringCompletedEventArgs获取错误Uri

时间:2010-08-16 20:36:46

标签: c# webclient

基本上我想记录测试时产生错误的uri,使用调试器我可以找到失败的uri,但我不知道如何检索它,这里是下面的打印屏幕

http://img802.imageshack.us/img802/5465/progps.jpg

建议表示赞赏。

3 个答案:

答案 0 :(得分:1)

(e.Error.Response as HttpWebResponse).ResponseUri

答案 1 :(得分:1)

调用重载WebClient.DownloadStringAsync(Uri),而不是调用DownloadString(Uri, Object),将Uri作为第二个参数传递。然后,在事件处理程序中,您可以将e.UserToken的值强制转换为Uri以检索该值。那就是:

Uri uri = new Uri("http://example.com");
WebClient client = new WebClient();
client.DownloadStringCompleted = StringDownloaded;
client.DownloadStringAsync(uri, uri);


void StringDownloaded(object sender, DownloadStringCompletedEventArgs e)
{
    Uri uri = (Uri)e.UserToken;

    ...
}

您可以使用此技术将任何类型的状态传递给事件处理程序。

答案 2 :(得分:1)

Ash在Jim Mischel的回答中所说的是,在e.UserState中可以访问传递给事件处理函数中的DownloadStringAsync的UserToken(在DownloadStringCompletedEventArgs对象e上不存在e.UserToken)。

即。这有效:

Uri uri = new Uri("http://example.com");
WebClient client = new WebClient();
client.DownloadStringCompleted = StringDownloaded;
client.DownloadStringAsync(uri, uri);


void StringDownloaded(object sender, DownloadStringCompletedEventArgs e){
    Uri uri = (Uri)e.UserState;
    ...
}