![](https://images.cnblogs.com/OutliningIndicators/ContractedBlock.gif)
/// <summary> /// 文件下载 /// </summary> /// <param name="filePath">物理路径(推荐使用Server.MapPath)</param> /// <param name="isBinaryWrite">是否采用二进制的方式输出(一般为false,对某些特殊的文件如pdf可设置为true)</param> public static void OutPutFile(string filePath, bool isBinaryWrite) { if (string.IsNullOrEmpty(filePath)) return; FileInfo fi = new FileInfo(filePath); if (fi.Exists) { System.IO.Stream iStream = null; byte[] buffer = new Byte[10000]; int length; long dataToRead; 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; HttpContext.Current.Response.ContentType = "application/octet-stream"; HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=" + filename); while (dataToRead > 0) { if (HttpContext.Current.Response.IsClientConnected) { length = iStream.Read(buffer, 0, 4096); if (isBinaryWrite == false) HttpContext.Current.Response.OutputStream.Write(buffer, 0, length); else HttpContext.Current.Response.BinaryWrite(buffer); HttpContext.Current.Response.Flush(); buffer = new Byte[4096]; dataToRead = dataToRead - length; } else { dataToRead = -1; } } } catch (Exception ex) { // } finally { if (iStream != null) { iStream.Close(); } } } }