.Net 5.0 从api下载文件到本地

 1        /// <summary>
 2         /// 从Http下载文件
 3         /// </summary>
 4         /// <param name="url">文件链接</param>
 5         /// <param name="fileName">保存文件路径名</param>
 6         /// <returns></returns>
 7         public static string HttpDownFile(string url,string fileName)
 8         {
 9            // url = "https://paper.ysbang.cn/data/img/report/user/2018/07/16/5b4c078549c55_6531.jpg";
10             var request = (HttpWebRequest)WebRequest.Create(url);
11             
12             request.Method = "GET";
13             using (var webRes = request.GetResponse())
14             {
15                 var length = (int)webRes.ContentLength;
16                 var response = webRes as HttpWebResponse;
17                 var stream = response?.GetResponseStream();
18                 var contentDisposition = response?.Headers["Content-Disposition"];
19                 var match = Regex.Match(contentDisposition ?? string.Empty, @"(?is)filename=""([^""]+)""\s*Content-Type:([^;]+)");
20                 fileName +="_"+ match.Groups[1].Value;
21 
22           
23                 //读取到内存
24                 var stmMemory = new MemoryStream();
25                 var buffer = new byte[length];
26                 int i;
27                 //将字节逐个放入到Byte中
28                 while (stream != null && (i = stream.Read(buffer, 0, buffer.Length)) > 0)
29                 {
30                     stmMemory.Write(buffer, 0, i);
31                 }
32                 stmMemory.ToArray();//文件流Byte
33                 var fs = new FileStream(fileName, FileMode.OpenOrCreate);
34                 stmMemory.WriteTo(fs);
35                 stmMemory.Close();
36                 fs.Close();
37                 return fileName;
38             }
39         }

 

.Net 5.0 从api下载文件到本地

上一篇:WinCMD Copy命令 复制/拷贝


下一篇:性能测试平台工具选型对比