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 需要写入权限