在Windows Phone中解析期间DownloadStrinAsync错误

时间:2013-06-02 12:25:35

标签: windows windows-phone-7 windows-phone

我有一个问题...我会创建一个应用程序来刮取谷歌搜索的结果..但是当我尝试使用downloadstringasync时,调试会返回一个错误“无法将'void'分配给局部变量......“

你说我怎么解决它?

这是代码

        public class SearchResult
    {
        public string url;
        public string title;
        public string content;
        public FindingEngine engine;

        public enum FindingEngine { google, bing, google_and_bing };

        public SearchResult(string url, string title, string content, FindingEngine engine)
        {
            this.url = url;
            this.title = title;
            this.content = content;
            this.engine = engine;
        }
    }

public static List<SearchResult> GoogleSearch(string search_expression, 
  Dictionary<string, object> stats_dict)
{
  var url_template = "http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&safe=active&q={0}&start={1}";
  Uri search_url;
  var results_list = new List<SearchResult>();
  int[] offsets = { 0, 8, 16, 24, 32, 40, 48 };
  foreach (var offset in offsets)
  {

    var searchUrl = new Uri(string.Format(url_template, search_expression, offset));
    var page = new WebClient().DownloadStringAsync(searchUrl);
    var o = (JObject)JsonConvert.DeserializeObject(page);

    var results_query =
      from result in o["responseData"]["results"].Children()
      select new SearchResult(
          url: result.Value<string>("url").ToString(),
          title: result.Value<string>("title").ToString(),
          content: result.Value<string>("content").ToString(),
          engine: SearchResult.FindingEngine.google
          );

    foreach (var result in results_query)
      results_list.Add(result);
  }

  return results_list;
}

谢谢!

1 个答案:

答案 0 :(得分:1)

DownloadStringAsync不返回任何内容,即void,因此您无法简单地为其分配变量。

您需要向DownloadStringCompleted添加一个事件处理程序,该事件处理程序将在DownloadStringAsync完成时触发。

var client = new WebClient();
client.DownloadStringCompleted += client_DownloadStringCompleted;
client.DownloadStringAsync(searchUrl);

static void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) {
  // e.Result will contain the returned JSON. Move the code that parse the result to here.
}