WebClient doesn't seem to work?

I have the following code:

WebClient client = new WebClient();
client.OpenReadAsync(new Uri("whatever"));
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);

and

void client_OpenReadCompleted(object sender, OpenReadCompletedEventArgs e)
{
  Stream reply = (Stream)e.Result;
  StreamReader s;
  s = new StreamReader(reply);
  this._code = s.ReadToEnd();
  s.Close();
}

During debugging, I see that the compiler is not moving to the event client_OpenReadCompleted. Where is the mistake? I already tried to use DownloadStringCompletedand DownloadStringAsyncinstead, but this also does not work.

Thank you for your help.

+3
source share
3 answers

I would advise you not to use WebClient, as this adversely affects your user interface, because the callback will always be returned in the user interface thread due to an error.

It explains why and how you can use HttpWebRequest as an alternative

http://social.msdn.microsoft.com/Forums/en-US/windowsphone7series/thread/594e1422-3b69-4cd2-a09b-fb500d5eb1d8

0

, async.

WebClient client = new WebClient();
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
client.OpenReadAsync(new Uri("www.google.it"));

EDIT: LINQPad, .

void Main()
{
    var client = new System.Net.WebClient();
    client.OpenReadCompleted += (sender, e) =>
    {
        "Read successfully".Dump();
    };
    client.OpenReadAsync(new Uri("http://www.google.it"));
    Console.ReadLine();
}

, ?

+1

Incorrect order of operations.

//create an instance of webclient
WebClient client = new WebClient();
//assign the event handler
client.OpenReadCompleted += new OpenReadCompletedEventHandler(client_OpenReadCompleted);
//call the read method
client.OpenReadAsync(new Uri("whatever"));
+1
source

All Articles