using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using System.IO; public partial class DFile : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } protected void LinBtnDFile_Click(object sender, EventArgs e) { // 創建一比特數組 byte[] buffer = new Byte[10240]; // 指定要下載文件的路徑. string filePath = @"D:\愛智旮旯.rar"; // 或取文件名包括擴展名 string fileName = Path.GetFileName(filePath); Stream fileStream = null; try { // 打開文件 fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); Response.Clear(); // 獲取文件的大小 long fileSize = fileStream.Length; long sum = 0; if (Request.Headers["Range"] != null) { Response.StatusCode = 206; // 表示返回到客戶端的 HTTP 輸出狀態的整數。默認值為 200。 sum = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); } if (sum != 0) { Response.AddHeader("Content-Range", "bytes " + sum.ToString() + "-" + ((long)(fileSize)).ToString() + "/" + fileSize.ToString()); } // 獲取部分http頭信息 Response.AddHeader("Content-Length", ((long)(fileSize - sum)).ToString()); Response.ContentType = "application/octet-stream"; //獲取文件來源 Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(Request.ContentEncoding.GetBytes(fileName))); // Response.Flush(); fileStream.Position = sum; //設置當前流位置 fileSize = fileSize - sum; // 當文件大小大於0是進入循環 while (fileSize > 0) { // 判斷客戶端是否仍連接在服務器 if (Response.IsClientConnected) { // 獲取緩沖區中的總字節數. int length = fileStream.Read(buffer, 0, 10240); // 寫入數據 Response.OutputStream.Write(buffer, 0, length); // 將緩沖區的輸出發送到客戶端 Response.Flush(); buffer = new Byte[10240]; fileSize = fileSize - length; } else { //當用戶斷開後退出循環 fileSize = -1; } } } catch (Exception ex) { Response.Write("Error : " + ex.Message); } finally { if (fileStream != null) { //關閉文件 fileStream.Close(); } Response.End(); } } }
qq:652346044
百度搜索 “C# 斷點續傳”,希望搜索結果能夠幫到你。