Trouble with WebClient.DownloadDataAsync(). Not downloading the data?

前提是你 提交于 2019-12-24 17:27:12

问题


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! :D


回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/1586184/trouble-with-webclient-downloaddataasync-not-downloading-the-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!