下载文件时提示"无法复制文件,无法读取文件或磁盘"的错误解决方案

本文介绍了一种使用ASP.NET实现文件下载的方法。通过设置HTTP响应头部信息和利用FileStream读取文件内容,实现了对指定路径下文件的安全下载。适用于需要提供文件下载功能的Web应用程序。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;

namespace infoPlatClient.NetDisk
{
    public partial class downLoad : Com.DRPENG.Common.WebStruct.BaseForm
    {

        /// <summary>
        /// 取得要下载文件的路径
        /// </summary>
        private string fileRpath
        {
            get
            {
                return Request["fileRpath"] == null ? "" : Request["fileRpath"];
            }
        }
        /// <summary>
        /// 取得要下载文件的名称
        /// </summary>

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
                DownLoad();
        }


        private void DownLoad()
        {
            string name = System.IO.Path.GetFileName(fileRpath);
            System.IO.FileInfo fileInfo = new System.IO.FileInfo(fileRpath);
            if (fileInfo.Exists == true)
            {
                const long ChunkSize = 102400;//100K 每次读取文件,只读取100K,这样可以缓解服务器的压力
                byte[] buffer = new byte[ChunkSize];

                Response.Clear();
                System.IO.FileStream iStream = System.IO.File.OpenRead(fileRpath);
                long dataLengthToRead = iStream.Length;//获取下载的文件总大小
                Response.ContentType = "application/octet-stream;charset=gbk";
                Response.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                while (dataLengthToRead > 0 && Response.IsClientConnected)
                {
                    int lengthRead = iStream.Read(buffer, 0, Convert.ToInt32(ChunkSize));//读取的大小
                    Response.OutputStream.Write(buffer, 0, lengthRead);
                    Response.Flush();
                    dataLengthToRead = dataLengthToRead - lengthRead;
                }
                Response.Close();
            }
        }

    }
}
主要是这段代码:  Response.ContentType = "application/octet-stream;charset=gbk";

转载于:https://www.cnblogs.com/zhangzt/archive/2010/01/06/1640463.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值