1.废话不多说,直接上代码:
1 using System; 2 using System.IO; 3 using System.Net; 4 5 namespace AsyncProgram 6 { 7 class Program 8 { 9 static void Main(string[] args) 10 { 11 do 12 { 13 Console.WriteLine("请输入要下载的文件地址,输入quit退出!"); 14 string url = Console.ReadLine(); 15 16 if (url == "quit") break; 17 18 if (!url.StartsWith("http://")) 19 { 20 Console.WriteLine("只能支持http://开头的下载地址!"); 21 continue; 22 } 23 24 string []strs = url.Split(new char[] { '/'},StringSplitOptions.RemoveEmptyEntries); 25 string fileName = strs[strs.Length-1]; 26 27 WebRequest webRequest = WebRequest.Create(url); 28 29 webRequest.BeginGetResponse(DownloadFinished, new Mystate { FileName = fileName, WebRequestObject = webRequest }); 30 31 Console.WriteLine($"已在后台自动下载文件:{fileName}\r\n"); 32 33 } while (true); 34 35 Console.WriteLine("正在下载文件..."); 36 37 Console.WriteLine("关闭次窗口前,请确保文件已全部下载完成!按任意键关闭窗口..."); 38 39 Console.ReadKey(); 40 41 } 42 43 static void DownloadFinished(IAsyncResult ar) 44 { 45 try 46 { 47 Mystate state = ar.AsyncState as Mystate; 48 WebResponse response = state.WebRequestObject.EndGetResponse(ar); 49 50 Stream inStream = response.GetResponseStream(); 51 byte[] buffer = new byte[1024*1024]; 52 Stream outStream = System.IO.File.Create(System.AppDomain.CurrentDomain.BaseDirectory + state.FileName); 53 try 54 { 55 int l; 56 do 57 { 58 l = inStream.Read(buffer, 0, buffer.Length); 59 if (l > 0) outStream.Write(buffer, 0, l); 60 } while (l > 0); 61 } 62 finally 63 { 64 if (outStream != null) outStream.Close(); 65 if (inStream != null) inStream.Close(); 66 } 67 68 } 69 catch (Exception ex) 70 { 71 Console.WriteLine(ex.Message); 72 } 73 } 74 } 75 76 public class Mystate 77 { 78 public string FileName { get; set; } 79 public WebRequest WebRequestObject { get; set; } 80 } 81 }