代码改变世界

文件下载

2012-05-04 12:23  Carl Xing  阅读(189)  评论(0编辑  收藏  举报
protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                using (FileStream fs = new FileStream(Server.MapPath("~/123.txt"), FileMode.OpenOrCreate))
                {
                    int streamLength = (int)fs.Length;
                    byte[] buffer = new byte[streamLength];
                    fs.Read(buffer, 0, streamLength);
                    HttpContext.Current.Response.ContentType = "application/octet-stream";
                    HttpContext.Current.Response.AddHeader("Content-Disposition", "attachment; filename=777.txt;");
                    ////attachment --- 作为附件下载
                    ////inline --- 在线打开
                    HttpContext.Current.Response.AddHeader("Content-Length", streamLength.ToString());
                    Response.BinaryWrite(buffer);
                    fs.Close();
                    Response.Flush();
                    Response.End();
                }
            }
        }