之前没用过ProgressBar,前几天做数据下载当时测试用的下载文件比较小,基本上不显示进度条,后来发现可以设置每次下载的量,如果非想看到进度条的话,代码如下:
public class DownFile { public delegate void DownFileDelegate(); public event DownFileDelegate onDownFileCompleted; public String DownFileName; public void DownloadFile(string URL, string filename, System.Windows.Forms.ProgressBar prog) { try { DownFileName = filename; prog.Show(); 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; int size = prog.Maximum / 1000; byte[] by = new byte[size]; 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; prog.PerformStep(); } osize = st.Read(by, 0, (int)by.Length); } so.Close(); st.Close(); myrp.Close(); if (prog.Value == prog.Maximum) { if (onDownFileCompleted != null) { onDownFileCompleted(); } } } catch (System.Exception) { throw; } } }