Reputation: 25
I'm trying to download some HTML source code with DownloadStringAsync. My code looks like this:
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");
}
If I look at the variable "source" I can see that some of the source is there, but not all. However, if I do something like this it works:
while (true)
{
source = wb.DownloadString(url);
if (source.Contains("<!-- Inline markers start rendering here. -->"))
break;
}
Unfortunately I can't use that approach since WP8 don't have DownloadString.
Does anyone know how to fix this or if there is a better approach?
Upvotes: 2
Views: 1283
Reputation: 1201
This function should help you out
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;
}
Upvotes: 2