wp8通过WebClient从服务器下载文件
2015-01-07 20:31
363 查看
通过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(); } } }
相关文章推荐
- WinFrom通过WebClient向Web服务器上传下载文件
- 【转】WinFrom通过WebClient向Web服务器上传下载文件(带进度条)
- WinFrom通过WebClient向Web服务器上传下载文件(带进度条)
- ubuntu下通过ssh登录服务器并通过tftp上传下载文件
- C# WinForm通过WebClient实现文件上传下载 (附源码)
- 通过zssh在服务器和本地之间上传和下载文件
- WebClient上传文件至服务器和下载服务器文件至客户端
- C# WinForm通过WebClient实现文件上传下载 (附源码)
- 如何在html中通过下载对话框来下载服务器端的文件
- 通过FTP将一个数据文件从A服务器下载到B服务器的整个过程
- C# WinForm通过WebClient实现文件上传下载 (附源码) 分类: C#.NET
- 通过WebClient模拟post上传文件到服务器
- 通过设置http的头信息实现服务器不保存文件直接下载
- java 通过sftp服务器上传下载删除文件
- c#通过URL地址从服务器上下载文件
- Java通过FTP服务器上传下载文件的方法
- 下载服务器文件至客户端/WebClient上传文件至服务器
- 下载(二)客户端通过C# 代码直接从服务器下载文件到本地
- 下载(二)客户端通过C# 代码直接从服务器下载文件到本地
- 通过a连接下载服务器上的pdf文件