Today the main record, share two ways to use WebClient to download / get files.
Man of few words said, place the code.
The first: use WebClient from encapsulation methods: the DownloadFile () ; easy to download directly.
/// <the Summary> /// download the file (WebClient.DownloadFile) /// </ the Summary> /// <param name = "downFileUrl"> Download file link address </ param> /// <param name = " savePath "> save path </ param> /// <Returns> </ Returns> public static String DownLoadFileByWebClientStatic ( String downFileUrl, String savepath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); wcClient.DownloadFile(downFileUrl, savePath); the Result = " download success " ; } catch (WebException ex) { Result = $ " download failed ex.Message {} = Error! " ; } return result; } /// <the Summary> /// download the file (wcClient.DownloadFileAsync) /// </ the Summary> /// <param name = "downFileUrl"> Download file link address </ param> /// <param name = " savePath "> save path </ param> /// <Returns> </ Returns> public static String DownLoadFileMethod ( String downFileUrl, String savepath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); wcClient.DownloadDataCompleted += (t, s) => { the Result = " download success " ; // does not directly return (stateless?) }; wcClient.DownloadFileAsync(new Uri(downFileUrl), savePath); } catch (WebException ex) { Result = $ " download failed ex.Message {} = Error! " ; } return result; }
The second: use to read files streamed download / get the file . (Through self-test)
/// <Summary> /// download file (Stream Processing form) /// </ Summary> /// <param name = "downFileUrl"> download the file link address </ param> /// <param name = " savePath "> save path </ param> /// <Returns> </ Returns> public static String DownLoadFileByWebClient ( String downFileUrl, String savepath) { string result = string.Empty; try { WebClient wcClient = new WebClient(); WebRequest webReq = WebRequest.Create(downFileUrl); WebResponse webRes = webReq.GetResponse(); long fileLength = webRes.ContentLength; Stream srm = webRes.GetResponseStream(); StreamReader srmReader = new StreamReader(srm); byte[] bufferbyte = new byte[fileLength]; int allByte = (int)bufferbyte.Length; int startByte = 0; while (fileLength > 0) { int downByte = srm.Read(bufferbyte, startByte, allByte); if (downByte == 0) break; start byte + = down byte; allByte -= downByte; } // detect the existence of the directory where to save the file IF (! File.Exists (savepath)) { string[] dirArray = savePath.Split('\\'); string temp = string.Empty; for (int i = 0; i < dirArray.Length - 1; i++) { temp += dirArray[i].Trim() + "\\"; if (!Directory.Exists(temp)) Directory.CreateDirectory(temp); } } using (FileStream fsSave = new FileStream(savePath, FileMode.OpenOrCreate, FileAccess.Write)) { fsSave.Write(bufferbyte, 0, bufferbyte.Length); fsSave.Dispose (); } // equivalent to using both methods. // the FileStream new new FS = the FileStream (savepath, FileMode.OpenOrCreate, FileAccess.Write); // fs.Write (bufferbyte, 0, bufferbyte.Length); srm.Close (); srmReader.Close(); // fs.Close (); Result = $ " download success savepath {} = path " ; } catch (WebException ex) { Result = $ " download failed ex.Message {} = Error! " ; } return result; }
The second stream by downloading files, the method branches to obtain :( use of OpenRead WebClient () way to Stream, and then read the file stream, I do not know why , self-test failed , download the file does not open). I have not found a reasonable explanation, I hope you comment.
/// <the Summary> /// download file /// </ the Summary> /// <param name = "URLAddress"> resources the URL of </ param> /// <param name = "saveBasePath"> Save the root directory / directory </ param> /// <Returns> </ Returns> public String DownFileByStream ( String URLAddress, String saveBasePath) { string result = string.Empty; try { WebClient client = new WebClient(); Stream str = client.OpenRead(URLAddress); StreamReader reader = new StreamReader(str); byte [] bytes = new new byte [ 1024 * 1024 ]; // custom size 1M int allybytes = ( int ) bytes.Length; int startbytes = 0 ; while (allybytes > 0) { int m = str.Read (bytes, startbytes, allybytes); // get the current position of the read byte IF (m == 0 ) BREAK ; start bytes + = m; allybytes -= m; } reader.Dispose(); str.Dispose(); string path = saveBasePath + System.IO.Path.GetFileName(URLAddress); FileStream fsWrite = new FileStream(path, FileMode.OpenOrCreate, FileAccess.Write); fsWrite.Write(bytes, 0, startbytes); fsWrite.Flush(); fsWrite.Close(); the Result = " download success! " ; } catch (Exception ex) { the Result = " Download failure! " + ex.Message; } return result; }
If unreasonable, welcome that. These are today's record; most of the contents of this article can be found to the just here to do a little finishing.
If you think this article helpful to you, please click on "Favorites" button! (/: Smile) welcome to reprint, please indicate the source.