【问题标题】:Port this from WP7 to Windows 8将此从 WP7 移植到 Windows 8
【发布时间】:2012-12-17 22:44:50
【问题描述】:

我找不到如何从此代码中替换 Webclient。

什么是新的命名空间以及在 Windows 8 中创建它的方法...... Win 8 dev 的新功能。

任何提示或帖子都会有所帮助,或者下面的任何代码。

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;





      } 
    } 
} 

【问题讨论】:

    标签: c# xml windows linq windows-8


    【解决方案1】:

    您可以使用 HTTPClient 代替 WebClient,如下所示:

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

    这也是另一个非常相似的问题:WebClient class doesn't exist in Windows 8

    【讨论】:

    • 谢谢....虽然我收到此错误...“等待”运算符只能在异步方法中使用。考虑使用“async”修饰符标记此方法并将其返回类型更改为“Task”。
    • 如果您在函数中有此代码,则必须将函数更改为以下内容: public async Task DownloadMyStuff(){ // 代码在这里 }
    • 我更新了答案,将其写为一个异步函数,该函数返回下载的字符串。有关使用异步的更多信息,请参阅msdn.microsoft.com/en-us/library/vstudio/hh191443.aspx
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-04
    • 2015-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多