wp8通过WebClient从服务器下载文件

通过WebClient从Web服务器下载文件,并保存到wp8手机应用程序的独立存储。

我们可以通过利用webClient_DownloadStringCompleted来获得下载完成所需要的时间,用Stopwatch得到下载的总时间。
通常我们都将上传、下载作为异步事件来处理,以便不阻止主线程。

String url = "http://172.18.144.248:8080/upload/" + filename;
WebClient client = new WebClient();
client.Encoding = System.Text.Encoding.UTF8;
client.DownloadStringCompleted += new DownloadStringCompletedEventHandler(this.webClient_DownloadStringCompleted);
Stopwatch sw;
sw = Stopwatch.StartNew();//用来记录总的下载时间

public static Task<string> DownloadStringTask(this WebClient webClient, Uri uri)
{
    var tcs = new TaskCompletionSource<string>();
    webClient.DownloadStringCompleted += (s, e) =>
    {
        if (e.Error != null)
        {
            tcs.SetException(e.Error);
         }
         else
         {
             tcs.SetResult(e.Result);
          }
      };
      webClient.DownloadStringAsync(uri);
      return tcs.Task;
}

public void webClient_DownloadStringCompleted(object s, DownloadStringCompletedEventArgs e)
{
    sw.Stop();
    long totaltime = sw.ElapsedMilliseconds;        
    MessageBox.Show(totaltime+"ms,download succeed!");
}
webClient.DownloadStringAsync(uri)得到的是字符串,我们将其保存到独立存储中,通过 await IsolatedStorageHelper.writeFileAsync(filename,cont)异步执行,通过writeFileAsync函数写入独立存储。

        public async static Task writeFileAsync(String fileName, String text)
        {
            using (IsolatedStorageFile isolatedStorageFile = IsolatedStorageFile.GetUserStoreForApplication())
            {
                  if (isolatedStorageFile.FileExists(fileName))
                {
                    isolatedStorageFile.DeleteFile(fileName);
                }         
                using (IsolatedStorageFileStream isolatedStorageFileStream = isolatedStorageFile.CreateFile(fileName))
                {
                     using (StreamWriter streamWriter = new StreamWriter(isolatedStorageFileStream,System.Text.Encoding.UTF8))                  
                     {                             
                          streamWriter.Write(text);
                          streamWriter.Close();
                     }                   
                     isolatedStorageFileStream.Close();
                     isolatedStorageFileStream.Dispose();
                   
                }
            }
        }



郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。