1. 程式人生 > >C#實現檔案下載

C#實現檔案下載

        /// <summary>
        /// 使用OutputStream.Write分塊下載檔案  
        /// </summary>
        /// <param name="filePath"></param>
        public void WriteFileBlock(string filePath)
        {
            filePath = Server.MapPath(filePath);
            if (!File.Exists(filePath))
            {
                
return; } FileInfo info = new FileInfo(filePath); //指定塊大小 long chunkSize = 4096; //建立一個4K的緩衝區 byte[] buffer = new byte[chunkSize]; //剩餘的位元組數 long dataToRead = 0; FileStream stream = null;
try { //開啟檔案 stream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read); dataToRead = stream.Length; //新增Http頭 HttpContext.Current.Response.ContentType = "application/octet-stream
"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachement;filename=" + Server.UrlEncode(info.FullName)); HttpContext.Current.Response.AddHeader("Content-Length", dataToRead.ToString()); while (dataToRead > 0) { if (HttpContext.Current.Response.IsClientConnected) { int length = stream.Read(buffer, 0, Convert.ToInt32(chunkSize)); HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); HttpContext.Current.Response.Flush(); HttpContext.Current.Response.Clear(); dataToRead -= length; } else { //防止client失去連線 dataToRead = -1; } } } catch (Exception ex) { HttpContext.Current.Response.Write("Error:" + ex.Message); } finally { if (stream != null) { stream.Close(); } HttpContext.Current.Response.Close(); } }