C# Winform下载文件并显示进度条
首页要在窗体上拖progressBar、label和button三个控件,拖到适当的位置
双击button按纽,在里面加上代码
private void button1_Click(object sender, EventArgs e)
{
//点击开始下载
string url = "http://www.aspbc.com/1.rar";//这里换成你要下载的文件
DownloadFile(url, @"F:\" + System.IO.Path.GetFileName(url), progressBar1, label1);
}
/// <summary>
/// c#.net 下载文件
/// </summary>
/// <param name="URL">下载文件地址</param>
/// <param name="Filename">下载后的存放地址</param>
/// <param name="Prog">用于显示的进度条</param>
public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog, System.Windows.Forms.Label label1)
{
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;
string s2 = String.Format("{0:N2}", percent);
label1.Text = "正在下载,下载进度" + s2 + "%";
System.Windows.Forms.Application.DoEvents(); //必须加注这句代码,否则label1将因为循环执行太快而来不及显示信息
}
so.Close();
st.Close();
//下载完成
label1.Text = "下载完成";
}
catch (System.Exception)
{
throw;
}
}
中国· 上海
CopyRight©2009-2019 上海谷谷网络科技有限公司 All Rights Reserved. 沪ICP备11022482号-8
- top
- 在线咨询
-
添加微信咨询