2012-12-17 176 views
0

我找不到如何从此代码中取代Webclient。从WP7移植到Windows 8

什么是新的命名空间和在Windows 8中创建它的方法....新的Win 8开发。

任何提示或帖子将有帮助,或下面的任何代码。

WebClient client = new WebClient(); 
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(client_DownloadStringCompleted); 
Uri url2 = new Uri("http://www.buscms.com/api/XmlEntities/v1/stops.aspx", UriKind.Absolute); 
client.DownloadStringAsync(url2); 


void client_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e) 
{ 
    if (e.Error == null) 
    { 
     if (e.Result != null) 
     { 
      XDocument doc = XDocument.Parse(e.Result); 
      XNamespace ns = "http://schemas.datacontract.org/2004/07/BusExpress.ClassLibrary"; 
      var routeNames = (from n in doc.Descendants(ns + "ArrayOfStop") 
          select new RootContainer2 
          { 
           Departures = (from s in n.Elements(ns + "Stop") 
              select new Departures 
              { 

               StopName = s.Element(ns + "StopName").Value,  

              }).ToList() 
          }).Single(); 

      listBox2.ItemsSource = routeNames.Departures; 





     } 
    } 
} 

回答

2

可以使用的HttpClient,而不是Web客户端,像这样:

public async Task<string> DownloadTheString() 
{ 
    HttpClient http = new System.Net.Http.HttpClient(); 
    HttpResponseMessage response = await http.GetAsync("http://www.buscms.com/api/XmlEntities/v1/stops.aspx"); 
    string result = await response.Content.ReadAsStringAsync(); 

    // Return the downloaded string 
    return result; 
} 

这里是另一个非常similair问题太:WebClient class doesn't exist in Windows 8

+0

谢谢....我虽然得到这个错误.. 'await'操作符只能在异步方法中使用。考虑使用“异步”修饰符标记此方法,并将其返回类型更改为“任务”。 –

+0

如果你有一个函数的代码,你必须将功能更改为类似这样: 公共异步任务 DownloadMyStuff(){// 代码在这里 } –

+0

我更新了它的答案写成返回一个异步函数下载的字符串。有关使用异步的更多信息,请参阅http://msdn.microsoft.com/zh-cn/library/vstudio/hh191443.aspx –