C# – Trouble with WebClient.DownloadDataAsync(). Not downloading the data

asynchronous, c++, webclient, winforms

public string[] SearchForMovie(string SearchParameter)
{
WebClientX.DownloadDataCompleted += new
DownloadDataCompletedEventHandler(WebClientX_DownloadDataCompleted);
WebClientX.DownloadDataAsync(new Uri(
"http://www.imdb.com/find?s=all&q=ironman+&x=0&y=0"));

    string sitesearchSource = Encoding.ASCII.GetString(Buffer);}void WebClientX_DownloadDataCompleted(object sender,    DownloadDataCompletedEventArgs e){    Buffer = e.Result;    throw new NotImplementedException();}

I get this exception:

The matrix cannot be null. Refering to my byte[] variable Buffer.

So, I can conclude that the DownloadDataAsync isn't really downloading anything. What is causing this problem?

PS. How can I easily format my code so it appear properly indented here. Why can't I just copy past the code from Visual C# express and maintain the indentation here? Thanks! 😀

Best Solution

The key word here is "async"; when you call DownloadDataAsync, it only starts the download; it isn't complete yet. You need to process the data in the callback (WebClientX_DownloadDataCompleted).

public string[] SearchForMovie(string SearchParameter){    WebClientX.DownloadDataCompleted += WebClientX_DownloadDataCompleted;    WebClientX.DownloadDataAsync(new Uri(uri));}void WebClientX_DownloadDataCompleted(object sender,     DownloadDataCompletedEventArgs e){    Buffer = e.Result;    string sitesearchSource = Encoding.ASCII.GetString(Buffer);}

Also - don't assume ASCII; WebClientX.Encoding would be better; or just DownloadStringAsync:

static void Main(){    var client = new WebClient();    client.DownloadStringCompleted += DownloadStringCompleted;    client.DownloadStringAsync(new Uri("http://google.com"));    Console.ReadLine();}static void DownloadStringCompleted(object sender,    DownloadStringCompletedEventArgs e){    if (e.Error == null && !e.Cancelled)    {        Console.WriteLine(e.Result);    }}