项目描述: 1 .用一个ListBox显示文件夹里德文件名列表 (已经实现)
           2 点击imageButton实现下载到本地的功能
 
出错情况:  点击imageButton时, 只出现列表再一次循环显示,没有实现下载保存本地的功能求高人指点 在线等待,不胜感激!代码如下
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;using System.IO;//  Directory类中Getfile方法  与FileInfo类public partial class DownLoad : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
      
            bindListBox();
           }
    //方法:  字符串数组的遍历 将File中的文件名添加在 Listbox中     protected void bindListBox()
    {
        //通过GetFile获取文件名
        string[] name = Directory.GetFiles(Server.MapPath("File"));        //将文件名循环显示在LISTbox列表中        foreach (string s in name)
        {
            LBFile.Items.Add(Path.GetFileName(s));
        }    }    //方法  实现下载功能    protected void dFile()
    {
        if (LBFile.SelectedValue != "") //判断选择文件名是否为空
        {
            if (Session["file"] != "")
            {
                //获取文件路径
                string path = Server.MapPath("File") + Session["file"].ToString();                //初始化 FileInfo  类的实例 它作为文件路径的包装                FileInfo fi = new FileInfo(path);                //判断文件是否存在                if (fi.Exists)
                {
                    //将文件保存到本机上
                    Response.Clear();
                    Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
                    Response.AddHeader("Content-Length", fi.Length.ToString());
                    Response.ContentType = "application/octet-stream";
                    Response.Filter.Close();
                    Response.WriteFile(fi.FullName);
                    Response.End();                }            }
        }        else
        {
            Page.RegisterStartupScript("","<script>alert('请选择文件名!')</script>");
        }
    }    
    //选中文件名保存到Session对象中    protected void listfile_SelectedIndexChangeed(object sender, EventArgs e)
    {        Session["file"] = LBFile.SelectedValue.ToString();
    }
    //点击下载
    protected void imgBtnDown_Click(object sender, ImageClickEventArgs e)
    {
        dFile();
    }
}

解决方案 »

  1.   

    程序运行到这一段了吗//判断文件是否存在  if (fi.Exists)
      {
      //将文件保存到本机上
      Response.Clear();
      Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(fi.Name));
      Response.AddHeader("Content-Length", fi.Length.ToString());
      Response.ContentType = "application/octet-stream";
      Response.Filter.Close();
      Response.WriteFile(fi.FullName);
      Response.End();  }
      

  2.   


    void 方法里 没办法设置断点 怎么看运行没到那里啊!
      

  3.   


    void 方法里 没办法设置断点 怎么看运行没到那里啊!
      

  4.   

    在dFile();里面设置断点.  点击imageButton就能调试中断
      

  5.   

    你的我没看
    这是我写的一个,你参考下吧
    #region DownLoad --- 下载文件    /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <returns></returns>
        public static bool DownLoad(string path)
        {
            return DownLoad(path, "", "");
        }    /// <summary>
        /// 下载文件
        /// </summary>
        /// <param name="path">路径</param>
        /// <param name="name">文件名</param>
        /// <param name="type">文件类型</param>
        /// <returns></returns>
        public static bool DownLoad(string path, string name, string type)
        {
            HttpRequest req = HttpContext.Current.Request;
            HttpResponse rep = HttpContext.Current.Response;
            name = string.IsNullOrEmpty(name) ? Path.GetFileName(path) : name;
            path = string.IsNullOrEmpty(type) ? path : (path.Substring(0, path.LastIndexOf(".")) + type);
            long speed = 1024 * 1024 * 100;
            try
            {
                if (!File.Exists(path)) { rep.Write("<span style=\"color:#ff0000;\">文件已丢失!</span>"); return false; }
                FileStream fs = new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.ReadWrite);
                if (fs.Length > long.MaxValue) { rep.Write("<span style=\"color:#ff0000;\">请求文件过大!</span>"); return false; }
                BinaryReader br = new BinaryReader(fs);
                try
                {
                    rep.AddHeader("Accept-Ranges", "bytes");
                    rep.Buffer = false;
                    long length = fs.Length;
                    long start = 0;
                    int pack = 102400;
                    int sleep = (int)Math.Floor(1000.0 * pack / speed) + 1;
                    if (req.Headers["Range"] != null) { rep.StatusCode = 206; string[] range = req.Headers["Range"].Split(new char[] { '=', '-' }); start = Convert.ToInt64(range[1]); }
                    rep.AddHeader("Content-Length", (length - start).ToString());
                    if (start != 0) { rep.AddHeader("Content-Range", string.Format("bytes {0}-{1}/{2}", start, length - 1, length)); }
                    rep.AddHeader("Connection", "Keep-Alive");
                    rep.ContentType = "application/octet-stream";
                    rep.AddHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(name, System.Text.Encoding.UTF8));
                    br.BaseStream.Seek(start, SeekOrigin.Begin);
                    int count = (int)Math.Floor((double)(length - start) / pack) + 1;
                    for (int i = 0; i < count; ) { if (rep.IsClientConnected) { rep.BinaryWrite(br.ReadBytes(pack)); System.Threading.Thread.Sleep(sleep); } else { break; } i++; if (i == count) { return true; } }
                }
                catch (Exception ex) { throw ex; }
                finally
                {
                    br.Close();
                    fs.Close();
                }
            }
            catch { return false; }
            return false;
        }
        #endregion
      

  6.   


    设置断点 显示运行到那个地方了 想问下 Response 那段代码的如果执行成功的话 会提示出对话框的显示吗
      

  7.   


    都是pool行的  怎么用在BUTTON的事件里呢?
      

  8.   


    if (string.IsNullOrEmpty(Request["path"])) { return; }
                string path = Security.DecryptQueryString(Request["path"]);
                string rename = string.IsNullOrEmpty(Request["rename"]) ? "" : Request["rename"];
                string retype = string.IsNullOrEmpty(Request["type"]) ? "" : (Request["type"].ToString() == "type" ? ".resx" : Request["type"].ToString());
                Global.DownLoad(Server.MapPath(path), rename, retype);