我正在尝试使用DownloadStringAsync下载一些HTML源代码。我的代码如下所示:
WebClient client = new WebClient();
client.DownloadStringCompleted +=
new DownloadStringCompletedEventHandler(DownloadStringCallback2);
client.DownloadStringAsync(new Uri(url));
private void DownloadStringCallback2(Object sender, DownloadStringCompletedEventArgs e)
{
source = (string)e.Result;
if (!source.Contains("<!-- Inline markers start rendering here. -->"))
MessageBox.Show("Nope");
else
MessageBox.Show("Worked");
}
如果我查看变量“source”,我可以看到一些源代码存在,但不是全部。但是,如果我做这样的事情就行了:
while (true)
{
source = wb.DownloadString(url);
if (source.Contains("<!-- Inline markers start rendering here. -->"))
break;
}
不幸的是我不能使用这种方法,因为WP8没有DownloadString。
有谁知道如何解决这个问题,或者是否有更好的方法?
答案 0 :(得分:2)
此功能可以帮助您
public static Task<string> DownloadString(Uri url)
{
var tcs = new TaskCompletionSource<string>();
var wc = new WebClient();
wc.DownloadStringCompleted += (s, e) =>
{
if (e.Error != null) tcs.TrySetException(e.Error);
else if (e.Cancelled) tcs.TrySetCanceled();
else tcs.TrySetResult(e.Result);
};
wc.DownloadStringAsync(url);
return tcs.Task;
}