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

来源:互联网 发布:超市收银软件多少钱 编辑:程序博客网 时间:2024/05/17 05:11

通过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();                                   }            }        }



1 0