[c#]代码库
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.Diagnostics;
namespace MyDownload
{
public partial class MyDownload : Form
{
string Url = ""; //要下载的文件的地址
string filePath = ""; //下载后文件保存地址
//private const string applicationFile = "LMS";
/// <summary>
/// 构造函数
/// </summary>
/// <param name="Url"></param>
/// <param name="filePath"></param>
public MyDownload(string Url, string filePath)
{
InitializeComponent();
this.label1.Text = "";
this.Url = Url;
this.filePath = filePath;
}
/// <summary>
/// 清楚已有文件
/// </summary>
/// <param name="filepath"></param>
private void RemoveSetupFile(string filepath)
{
try
{
string folder = new DirectoryInfo(filepath).FullName;
//if (File.Exists(folder + @"\" + applicationFile + ".exe"))
//{
// File.Delete(folder + @"\" + applicationFile + ".exe");
//}
//if (File.Exists(folder + @"\" + applicationFile + ".msi"))
//{
// File.Delete(folder + @"\" + applicationFile + ".msi");
//}
if(File.Exists(folder))
{
File.Delete(folder);
}
}
catch { }
}
/// <summary>
/// 下载
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btnDown_Click(object sender, EventArgs e)
{
RemoveSetupFile(filePath);
DownloadFile(Url, filePath);
Process.Start(filePath);
Application.Exit();
}
/// <summary>
/// c#,.net 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后的存放地址</param>
/// <param name="Prog">用于显示的进度条</param>
public void DownloadFile(string URL, string filename)
{
float percent = 0;
try
{
System.Net.HttpWebRequest Myrq = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(URL);
System.Net.HttpWebResponse myrp = (System.Net.HttpWebResponse)Myrq.GetResponse();
long totalBytes = myrp.ContentLength;
if (prog != null)
{
prog.Maximum = (int)totalBytes;
}
System.IO.Stream st = myrp.GetResponseStream();
System.IO.Stream so = new System.IO.FileStream(filename, System.IO.FileMode.Create);
long totalDownloadedByte = 0;
byte[] by = new byte[1024];
int osize = st.Read(by, 0, (int)by.Length);
while (osize > 0)
{
totalDownloadedByte = osize + totalDownloadedByte;
System.Windows.Forms.Application.DoEvents();
so.Write(by, 0, osize);
if (prog != null)
{
prog.Value = (int)totalDownloadedByte;
}
osize = st.Read(by, 0, (int)by.Length);
percent = (float)totalDownloadedByte / (float)totalBytes * 100;
label1.Text = "当前下载进度" + percent.ToString() + "%";
System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
}
so.Close();
st.Close();
}
catch (System.Exception)
{
throw;
}
this.Close();
}
/// <summary>
/// 取消
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void btn_Cancel_Click(object sender, EventArgs e)
{
Process.Start(filePath);
Application.Exit();
}
}
}
[源代码打包下载]
by: 发表于:2018-01-08 10:19:44 顶(0) | 踩(0) 回复
??
回复评论