1

公共字符串 [] SearchForMovie(字符串 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

4

1 回答 1

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);
    }
}
于 2009-10-18T22:35:22.970 回答