(原创)如何把数据放到web不能访问的文件夹中并给用户下载?

在应用中我们可能遇到这样的情况,我们需要临时生成一个数据文件给用户下载,但是每次下载都要判断,也就是说,用户并不能得到这个下载的url不断下载文件,下面是实现方法。文件保存为csv格式,方便数据导入导出,基本原理就是用流写入文件然后用Response.WriteFile把流发送到客户端。
表的结构同此文:http://www.cnblogs.com/lovecherry/archive/2005/03/25/125487.html


SqlConnection conn=new SqlConnection(System.Configuration.ConfigurationSettings.AppSettings["conn"]);
   SqlDataAdapter da=new SqlDataAdapter("select * from tb1",conn);
   DataSet ds=new DataSet();
   da.Fill(ds,"table1");
   DataTable dt=ds.Tables["table1"];
   string name=System.Configuration.ConfigurationSettings.AppSettings["downloadurl"].ToString()+DateTime.Today.ToString("yyyyMMdd")+new Random(DateTime.Now.Millisecond).Next(10000).ToString()+".csv";//存放到web.config中downloadurl指定的路径,文件格式为当前日期+4位随机数
   FileStream fs=new FileStream(name,FileMode.Create,FileAccess.Write);
   StreamWriter sw=new StreamWriter(fs,System.Text.Encoding.GetEncoding("gb2312"));
   sw.WriteLine("自动编号,姓名,年龄");
   foreach(DataRow dr in dt.Rows)
   {
    sw.WriteLine(dr["ID"]+","+dr["vName"]+","+dr["iAge"]);
   }
   sw.Close();
   Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(name));
   Response.ContentType = "application/ms-excel";// 指定返回的是一个不能被客户端读取的流,必须被下载
   Response.WriteFile(name); // 把文件流发送到客户端
   Response.End();

在这段代码前面你可以放置一些判断,判断是不是这个用户可以下载文件,生成的文件可以把名字存放到数据库中,下次可以直接下载而不要重复写文件了。
posted @ 2005-03-25 13:10  lovecherry  阅读(901)  评论(1编辑  收藏  举报