WebClient.DownloadDataAsync()遇到问题.不下载数据? [英] Trouble with WebClient.DownloadDataAsync(). Not downloading the data?

查看:203
本文介绍了WebClient.DownloadDataAsync()遇到问题.不下载数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我收到此异常:

矩阵不能为空.引用我的byte []变量Buffer.

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

因此,我可以得出结论,DownloadDataAsync并没有真正下载任何内容.是什么引起了这个问题?

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

PS.如何轻松格式化我的代码,使其在此处正确缩进.为什么我不能只复制Visual C#express中的代码并在此保留缩进?谢谢!:D

推荐答案

此处的关键字是异步";当您调用 DownloadDataAsync 时,它仅开始下载;还没有完成.您需要处理回调中的数据( WebClientX_DownloadDataCompleted ).

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

也-不要采用ASCII; WebClientX.Encoding 会更好;或只是 DownloadStringAsync :

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

这篇关于WebClient.DownloadDataAsync()遇到问题.不下载数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆