public static void DownLoadFile(string FileFullPath) { if (!string.IsNullOrEmpty(FileFullPath) && FileExists(FileFullPath)) { FileInfo fi = new FileInfo(FileFullPath);//文件信息 FileFullPath = HttpUtility.UrlEncode(Path.GetFileName(FileFullPath)); //對文件名編碼 FileFullPath = FileFullPath.Replace("+", "%20"); //解決空格被編碼爲"+"號的問題 HttpContext.Current.Response.Clear(); HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AppendHeader("Content-Disposition", "attachment; filename=" + FileFullPath); HttpContext.Current.Response.AppendHeader("content-length", fi.Length.ToString()); //文件長度 int chunkSize = 102400;//緩存區大小,可根據服務器性能及網絡狀況進行修改 byte[] buffer = new byte[chunkSize]; //緩存區 using (FileStream fs = fi.Open(FileMode.Open)) //打開一個文件流 { while (fs.Position >= 0 && HttpContext.Current.Response.IsClientConnected) //若是沒到文件尾而且客戶在線 { int tmp = fs.Read(buffer, 0, chunkSize);//讀取一塊文件 if (tmp <= 0) break; //tmp=0說明文件已經讀取完畢,則跳出循環 HttpContext.Current.Response.OutputStream.Write(buffer, 0, tmp);//向客戶端傳送一塊文件 HttpContext.Current.Response.Flush();//保證緩存所有送出 Thread.Sleep(10);//主線程休息一下,以釋放CPU } } } }
這是從某項目當中找到的一段代碼
在本機和測試環境 調用沒有問題緩存
在實際生產環境當中 IIS給了文件夾 USERS和IIS_IUSRS 讀取權限 結果怎麼都沒法下載文件
緣由:FileMode.Open 須要寫入權限服務器