首页 > 代码库 > c#文件下载
c#文件下载
IO流方式:
环境: 新建winform
代码:
1 using System; 2 using System.Collections.Generic; 3 using System.ComponentModel; 4 using System.Data; 5 using System.Drawing; 6 using System.IO; 7 using System.Linq; 8 using System.Net; 9 using System.Text; 10 using System.Threading.Tasks; 11 using System.Windows.Forms; 12 13 namespace WindowsFormsApp1 14 { 15 public partial class Form2 : Form 16 { 17 public Form2() 18 { 19 InitializeComponent(); 20 } 21 22 private void Form1_Load(object sender, EventArgs e) 23 { 24 } 25 26 27 private void button3_Click(object sender, EventArgs e) 28 { 29 string path; 30 string FileName; 31 string Url; 32 string strName; 33 string finalName; 34 Url = "https://ss0.bdstatic.com/70cFuHSh_Q1YnxGkpoWK1HF6hhy/it/u=72854971,1442321265&fm=23&gp=0.jpg"; 35 //Url = "http://vjs.zencdn.net/v/oceans.mp4"; 36 37 38 finalName =Url .Substring(Url .LastIndexOf(".")); //后缀名 39 strName = DateTime.Now.Ticks.ToString(); //前缀名 40 path = Environment.CurrentDirectory + "\\images\\"; 41 42 if(Directory.Exists(path) == false) 43 { 44 DirectoryInfo directoryInfo = new DirectoryInfo(path); 45 directoryInfo.Create(); 46 } 47 48 FileName = path + strName + finalName; 49 50 if (SavePhotoFromUrl(FileName, Url)) 51 { 52 MessageBox.Show("文件下载成功"); 53 } 54 else 55 { 56 MessageBox.Show("文件下载失败"); 57 58 } 59 } 60 61 62 public static bool SavePhotoFromUrl(string FileName, string Url) 63 { 64 bool Value = http://www.mamicode.com/false; 65 WebResponse response = null; 66 Stream stream = null; 67 68 try 69 { 70 HttpWebRequest request = (HttpWebRequest)WebRequest.Create(Url); 71 72 response = request.GetResponse(); 73 stream = response.GetResponseStream(); 74 75 if (!response.ContentType.ToLower().StartsWith("text/html")) 76 { 77 Value =http://www.mamicode.com/ SaveBinaryFile(response, FileName); 78 79 } 80 81 } 82 catch (Exception err) 83 { 84 string aa = err.ToString(); 85 } 86 return Value; 87 } 88 89 private static bool SaveBinaryFile(WebResponse response, string FileName) 90 { 91 bool Value = http://www.mamicode.com/true; 92 byte[] buffer = new byte[1024]; 93 94 try 95 { 96 if (File.Exists(FileName)) 97 File.Delete(FileName); 98 Stream outStream = System.IO.File.Create(FileName); 99 Stream inStream = response.GetResponseStream(); 100 101 int l; 102 do 103 { 104 l = inStream.Read(buffer, 0, buffer.Length); 105 if (l > 0) 106 outStream.Write(buffer, 0, l); 107 } 108 while (l > 0); 109 110 outStream.Close(); 111 inStream.Close(); 112 } 113 catch 114 { 115 Value = http://www.mamicode.com/false; 116 } 117 return Value; 118 } 119 120 } 121 }
c#文件下载
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。