c# 文件下载

本文详细介绍了如何实现文件下载功能,包括获取文件路径、响应设置、异常处理及下载操作流程。同时,针对文件不存在的情况提供了错误提示。此外,还讨论了文件下载过程中可能出现的异常情况及其解决策略。

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

    /// <summary>
        /// 文件下载函数
        /// </summary>
        /// <param name="fileUrl"></param>
        /// <returns></returns>
        protected Boolean DowmLoad(string fileUrl)
        {
            Boolean dok = false;
            try
            {
                string fullPathUrl = Server.MapPath(fileUrl);//获取下载文件的路劲
                System.IO.FileInfo file = new System.IO.FileInfo(fullPathUrl);
                if (file.Exists)//判断文件是否存在
                {
                    Response.Clear();
                    Response.ClearHeaders();
                    Response.Buffer = false;
                    Response.AddHeader("content-disposition", "attachment;filename=" + file.Name);
                    Response.AddHeader("cintent_length", "attachment;filename=" + HttpUtility.UrlDecode(file.Name));
                    Response.AddHeader("cintent_length", file.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.WriteFile(file.FullName);//通过response对象,执行下载操作
                    Response.Flush();
                    Response.End();
                    dok = true;

                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "dd", "alert('文件不存在')", true);
                }
            }
            catch
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "dd", "alert('文件不存在')", true);
            }
            return dok;

        }

 

        protected void downLoad(int _articleID)
        {
            Model.mfr_article model = bll.GetModel(_articleID);
            if (model.fileName != "")
            {
                string downfiles = ConfigurationManager.AppSettings["ArticleWord"] + model.fileName;
                DowmLoad(downfiles);
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.GetType(), "msg", "alert('对不起,文档为空!')", true);
            }
        }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值