private void Button1_Click (object sender, EventArgs e) {dodownload (TextBox1.Text.Trim ()); } private DateTime StartTime; private void Dodownload (string url,string filename= "") {Label1. Text = "Downloading:" + url;//label box prompt to download the file if (filename.length==0) {fileName = URL. Substring (URL. LastIndexOf ("/") + 1); } StartTime = DateTime.Now; progressBar1.Value = 0;//Initializes a single file download bar WebClient ws = new WebClient (); Ws. DownloadProgressChanged + = ondownloadprogresschanged; Bind to set the Load event so that the current progress WS is displayed. downloadfilecompleted + = ondownloadfilecompleted; Binding to set the completion event to facilitate the calculation of the overall progress of WS. DownloadFileAsync (new Uri (URL), Path.Combine (AppDomain.CurrentDomain.BaseDirectory, fileName)); Call the DownloadFileAsync method to download the file//downloadfileasync There are 2 overloads, the other I don't understand the last parameter to pass what, any friend know, please leave a message to tell me thank you//upapp is my Entity class, UpdateUrl stores the downloaded address (a value ofhttp://www.harde.com.cn/SoftUpdate/)//path.combine () is a method for connecting addresses, which I'll explain in detail in another log}//download process change events private void Ondownloadprogresschanged (object sender, DownloadProgressChangedEventArgs e) {//See online To have a friend so to control the progress bar, I feel trouble, after all, there is a convenient why I have to trouble ...//this. Setprocessbar (e.progresspercentage, (int) ((ndownloadedtotal + e.bytesreceived) * 100/total)); progressBar1.Value = E.progresspercentage; var s = (datetime.now-starttime). TotalSeconds; var sd = readablefilesize (E.BYTESRECEIVED/S); Label1. Text = "Download Speed" +sd+ "/S" + ", downloaded" + readablefilesize (e.bytesreceived) + "/Total" + readablefilesize (e.totalbytestoreceive);// A label box to display the currently downloaded data}//download process Change event private void ondownloadfilecompleted (object sender, Asynccomplete Deventargs e) {MessageBox.Show ("complied!"); } private String Readablefilesize (double size) {string[] units = {"B", "KB", "MB "," GB "," TB "," PB "}; Double mod = 1024.0; int i = 0; while (size >= MoD) {size/= mod; i++;} return Math.Round (size) + units[i]; }
WebClient download file with progress bar