|
本帖最后由 FrankBoy 于 2016-6-13 12:46 编辑
最近在研究C#的Post ,闲暇之余写了一个简单的下载器与大家共同交流。
类: System.Net.Client
编译环境:vs2013 .Net Framework 4.0
贴出代码的意义纯属交流,希望能共获提升。
贴出的代码均已意义注释,如果还有什么不懂请帖子内回复,看到会一一回复。源码简单修改下封装为类,可以方便大家以后的使用。
源码:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Net;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace 下载工具
{
public partial class FrmMain : Form
{
public FrmMain()
{
InitializeComponent();
}
private void FrmMain_Load(object sender, EventArgs e)
{
}
private void button1_Click(object sender, EventArgs e)
{
string url = txtDownLoad.Text.Trim(); //获取编辑框内容并去除首尾空格赋值给url
WebClient webDown = new WebClient(); // 实例化一个 WebClient 对象
if (!string.IsNullOrWhiteSpace(url)) //判断 url 的内容不是null或者为空
{
try //获取输入的内容为无效的地址则会抛出异常
{
//使用异步的下载方式下载文件
webDown.DownloadFileAsync(new Uri(url), Application.StartupPath + "\\" + Path.GetFileName(url));
}
catch (Exception ex)
{
MessageBox.Show(ex.Message); //使用消息框显示出异常
}
webDown.DownloadFileCompleted += webDown_DownloadFileCompleted; //文件下载完成时执行的事件
webDown.DownloadProgressChanged += webDown_DownloadProgressChanged; //文件开始下载时发生
}
}
void webDown_DownloadFileCompleted(object sender, AsyncCompletedEventArgs e)
{
if (DialogResult.OK == MessageBox.Show("下载完成")) //判断弹出的信息框点击确定为真
{
toolStripProgressBar1.Value = 0; //进度条的Value值为0
}
}
void webDown_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
toolStripProgressBar1.Value = e.ProgressPercentage; //e.ProgressPercentage获取到下载进度的百分比赋值给进度条
}
}
}
|
-
-
Demo.7z
30.42 KB, 下载次数: 2, 下载积分: HB -3
源码下载
评分
-
参与人数 9 | HB +13 |
THX +4 |
收起
理由
|
消逝的过去
| |
+ 1 |
|
zxjzzh
| + 2 |
|
[吾爱汇编论坛52HB.COM]-软件反汇编逆向分析,软件安全必不可少! |
agan8888
| + 1 |
|
|
pmm018
| + 2 |
|
|
xpjkingstone
| + 1 |
+ 1 |
[快捷评语] - 吃水不忘打井人,给个评分懂感恩! |
freesilo
| + 1 |
|
[快捷评语] - 吃水不忘打井人,给个评分懂感恩! |
ronle
| + 1 |
|
分享精神,是最值得尊敬的! |
Bu弃
| + 4 |
+ 1 |
吃水不忘打井人,给个评分懂感恩! |
守护神艾丽莎
| + 1 |
+ 1 |
软件带有“学破解论坛网址”,置顶高亮7天7夜! |
查看全部评分
|