2012-12-17 168 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 –