http下载文件
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Text; using System.Threading.Tasks; namespace HttpDownload { class Program { static void Main(string[] args) { } public static void DownloadFile(string url,string fileName) { WebRequest webReq = WebRequest.Create(url); WebResponse webRes = webReq.GetResponse(); long fileLength = webRes.ContentLength; try { 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; }; startByte += downByte; allByte -= downByte; } string tempPath = fileName; CreateDirtory(tempPath); FileStream fs = new FileStream(tempPath, FileMode.OpenOrCreate, FileAccess.Write); fs.Write(bufferbyte, 0, bufferbyte.Length); srm.Close(); srmReader.Close(); fs.Close(); } catch (WebException ex) { } } //创建目录 private static void CreateDirtory(string path) { if (!File.Exists(path)) { string[] dirArray = path.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); } } } } }
相关推荐
-
用dockpanel suite实现标签窗体和浮动窗体的管理和状态保存 csharp
2019-1-7
-
清除某个文件夹下某种类型的文件 csharp
2019-1-7
-
C#串口通信扫码枪数据读取 csharp
2019-1-7
-
导出为EXCEL.cs csharp
2019-1-8
-
大数据 SqlBulkCopy方法 csharp
2019-1-7
-
C# 捕获全局异常 csharp
2019-1-8
-
dataTable转换成Json格式数据 csharp
2019-1-7
-
C#对象与二进制流间的转换 csharp
2019-1-7
-
ini配置文件操作类 csharp
2019-1-7
-
检测联网状态.cs csharp
2019-1-8