WebClient.DownloadDataAsync()的问题。没有下载数据?

时间:2009-10-18 22:20:37

标签: c# winforms asynchronous webclient

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。

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

PS。如何轻松地格式化我的代码,使其在此处显示正确缩进。为什么我不能只是从Visual C#express复制代码并在这里保留缩进?谢谢! :d

1 个答案:

答案 0 :(得分:3)

这里的关键词是“异步”;当您致电DownloadDataAsync时,只有启动下载;它尚未完成。您需要处理回调中的数据(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

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