/// <summary> /// 用流的方式下載文件 /// </summary> /// <param name="filepath_name">文件路徑及文件名</param> public static void FileDownLoad(string filepath_name) { System.IO.Stream iStream = null; //以10K為單位緩存: byte[] buffer = new Byte[10000]; int length; long dataToRead; // 制定文件路徑. string filepath = filepath_name; // 得到文件名. string filename = System.IO.Path.GetFileName(filepath); try { // 打開文件. iStream = new System.IO.FileStream(filepath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // 得到文件大小: dataToRead = iStream.Length; System.Web.HttpContext.Current.Response.ContentType = "application/octet-stream"; System.Web.HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); while (dataToRead > 0) { //保證客戶端連接 if (System.Web.HttpContext.Current.Response.IsClientConnected) { length = iStream.Read(buffer, 0, 10000); System.Web.HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); System.Web.HttpContext.Current.Response.Flush(); buffer = new Byte[10000]; dataToRead = dataToRead - length; } else { //結束循環 dataToRead = -1; } } } catch (Exception ex) { // 出錯. System.Web.HttpContext.Current.Response.Write("Error : " + ex.Message); } finally { if (iStream != null) { //關閉文件 iStream.Close(); } } }