http下载文件

csharp

浏览数:172

2019-1-7

AD:资源代下载服务
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);
                }
            }
        }
    }
}