URL文件保存到本地


 

string path = System.Web.HttpContext.Current.Server.MapPath("~/upload/文件名稱.文件擴展名");

 

        /// <summary>
        /// Http方式下載文件
        /// </summary>
        /// <param name="url">http地址</param>
        /// <param name="localfile">本地文件</param>
        /// <returns></returns>
        public bool Download(string url, string localfile)
        {
            bool flag = false;
            long startPosition = 0; // 上次下載的文件起始位置
            System.IO.FileStream writeStream; // 寫入本地文件流對象

            // 判斷要下載的文件夾是否存在
            if (System.IO.File.Exists(localfile))
            {
                writeStream = System.IO.File.OpenWrite(localfile);             // 存在則打開要下載的文件
                startPosition = writeStream.Length;                  // 獲取已經下載的長度
                writeStream.Seek(startPosition, System.IO.SeekOrigin.Current); // 本地文件寫入位置定位
            }
            else
            {
                writeStream = new System.IO.FileStream(localfile, System.IO.FileMode.Create);// 文件不保存創建一個文件
                startPosition = 0;
            }
            try
            {
                System.Net.HttpWebRequest myRequest = (System.Net.HttpWebRequest)System.Net.HttpWebRequest.Create(url);// 打開網絡連接

                if (startPosition > 0)
                {
                    myRequest.AddRange((int)startPosition);// 設置Range值,與上面的writeStream.Seek用意相同,是為了定義遠程文件讀取位置
                }

                System.IO.Stream readStream = myRequest.GetResponse().GetResponseStream();// 向服務器請求,獲得服務器的回應數據流
                byte[] btArray = new byte[512];// 定義一個字節數據,用來向readStream讀取內容和向writeStream寫入內容
                int contentSize = readStream.Read(btArray, 0, btArray.Length);// 向遠程文件讀第一次
                while (contentSize > 0)// 如果讀取長度大於零則繼續讀
                {
                    writeStream.Write(btArray, 0, contentSize);// 寫入本地文件
                    contentSize = readStream.Read(btArray, 0, btArray.Length);// 繼續向遠程文件讀取
                }
                //關閉流
                writeStream.Close();
                readStream.Close();
                flag = true;        //返回true下載成功
            }
            catch (Exception)
            {
                writeStream.Close();
                flag = false;       //返回false下載失敗
            }

            return flag;
        }

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM