The following code is derived from the network (http://www.cnblogs.com/hayden/archive/2012/04/26/2472815.html), pro-test easy to use. I have modified the following format and comments, the copyright belongs to the original author.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;usingSystem.IO;usingSystem.Net;namespaceconsoletest{classHttpdldfile {/// <summary> ///http way to download files/// </summary> /// <param name= "url" >HTTP Address</param> /// <param name= "LocalFile" >Local File</param> /// <returns></returns> Public BOOLDownload (stringUrlstringLocalFile) { BOOLFlag =false; LongStartPosition =0;//last downloaded file start locationFileStream Writestream;//write to local file stream object//determine if the folder you want to download exists if(File.exists (LocalFile)) {Writestream= File.openwrite (LocalFile);//exists then open the file you want to downloadStartPosition = Writestream.length;//get the length that has been downloadedWritestream.seek (StartPosition, seekorigin.current);//local File write location locator } Else{Writestream=NewFileStream (LocalFile, FileMode.Create);//file is not saved create a fileStartPosition =0; } Try{HttpWebRequest Myrequest= (HttpWebRequest) httpwebrequest.create (URL);//Open Network Connection if(StartPosition >0) {Myrequest.addrange (int) startposition);//set range value, same as above Writestream.seek, to define remote file read location} Stream Readstream= Myrequest.getresponse (). GetResponseStream ();//request to the server, get the response data stream of the server byte[] Btarray =New byte[ +];//defines a byte of data used to read content to Readstream and write content to Writestream intContentsize = Readstream.read (Btarray,0, btarray.length);//read the first time to a remote file while(Contentsize >0)//Continue reading if read length is greater than zero{writestream.write (Btarray,0, contentsize);//write to local fileContentsize = Readstream.read (Btarray,0, btarray.length);//continue to read to remote files } //Close the streamWritestream.close (); Readstream.close (); Flag=true;//return true Download succeeded } Catch(Exception) {writestream.close (); Flag=false;//return false Download failed } returnFlag; } }}
Test Code:usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Text;namespaceconsoletest{classProgram {Static voidMain (string[] args) {Httpdldfile DF=NewHttpdldfile (); Df. Download ("Http://files.cnblogs.com/files/xiandedanteng/Convertor20170624.zip","C:\\123\\convertor20170624.zip"); } }}
June 26, 2017 08:17:06
C # http way to download files to local