using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
namespace Shared.Net
{
///
/// 异步下载图片
///
public class DownLoadImageAsync
{
///
/// 当前的webClient对象
///
private System.Net.WebClient webClient = new WebClient();
///
/// 用户名
///
public string Name;
///
/// 密码
///
public string Password;
///
/// 地址
///
private Uri uri;
///
/// 异步下载图片
///
/// 链接地址
/// 登记用户名
/// 密码
public DownLoadImageAsync(Uri uri,string name,string password)
{
this.uri = uri;
this.Name = name;
this.Password = password;
}
///
/// 下载进度变化事件
///
public event DownloadProgressChangedEventHandler DownloadProgressChanged;
///
/// 下载完成
///
public event DownloadDataCompletedEventHandler DownloadDataCompleted;
///
/// 开始异步下载
///
public async void StartDownloadImageAsync()
{
// var url = new Uri("http://192.168.2.210/tmpfs/auto.jpg");
webClient.DownloadProgressChanged += HandleDownloadProgressChanged;
webClient.DownloadDataCompleted += webClient_DownloadDataCompleted;
try
{
string newValue = Convert.ToBase64String(System.Text.Encoding.ASCII.GetBytes(Name + ":" + Password));
webClient.Headers.Add("Content-Type", "image/webp,*/*;q=0.8");
webClient.Headers.Add("Accept-Encoding", "gzip,deflate,sdch");
webClient.Headers.Add("Authorization", "Basic " + newValue);
await webClient.DownloadDataTaskAsync(this.uri);
}
catch
{
DownloadDataCompleted("异步完成", null);
}
}
///
/// 下载图片完成
///
///
///
void webClient_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
if (DownloadDataCompleted != null)
{
DownloadDataCompleted(sender, e);
}
}
///
/// 下载进度变化
///
///
///
void HandleDownloadProgressChanged (object sender, DownloadProgressChangedEventArgs e)
{
if (DownloadProgressChanged != null)
{
DownloadProgressChanged(sender, e);
}
}
///
/// 取消下载
///
public void CancelDownload()
{
webClient.CancelAsync();
webClient.DownloadProgressChanged -= HandleDownloadProgressChanged;
}
}
}