using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data.SqlClient;
using System.Configuration;
using System.Text;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string path=Server.MapPath("dowm")+"//Users.txt"; //取得文件所在的路径
if (!File.Exists(path)) //判断文件是否存在
{
StreamWriter sw = new StreamWriter(path, false, Encoding.UTF8); //采用流方式创建一个对像path代表路径 ,false 代表是否进行append,Encoding枚举说明采用的
//编码方式
sw.Dispose(); 这是必要的一步如果没有这一步将会出错,所以用完了对像一定要立刻进行销毁(释放)
}
else
{
StreamWriter sw1 = new StreamWriter(path, false, Encoding.UTF8); //这里和上面的具有相同的意思
sw1.Write(""); //写空内容把文件里的内容清空
sw1.Dispose(); //同样这也是不可缺少的(释放)
string sqlcon = ConfigurationManager.ConnectionStrings["sqlcon"].ConnectionString;
using (SqlConnection con = new SqlConnection(sqlcon)) //创建数据连接
{
using (SqlCommand cmd = new SqlCommand("select * from users",con))
{
string record = ""; //串加器
SqlDataReader myreader;
con.Open();
myreader = cmd.ExecuteReader();
StreamWriter sw = File.AppendText(path); //创建一个流对像用来向其中append数据
while (myreader.Read())
{
record=myreader["uid"].ToString()+","+myreader["name"].ToString()+","+myreader["power"].ToString()+","+ myreader["lock"].ToString();
sw.WriteLine(record); //每次把串加器的内容写入txt中的一行中,
}
sw.Close(); //
sw.Dispose(); //
}
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
string fileName = "BaiNing.txt";//客户端保存的文件名
string filePath = Server.MapPath("dowm/Users.txt");//路径//以字符流的形式下载文件
FileStream fs = new FileStream(filePath, FileMode.Open); //创建文件流
byte[] bytes = new byte[(int)fs.Length];
fs.Read(bytes, 0, bytes.Length);
fs.Close();
Response.ContentType = "application/octet-stream";
//通知浏览器下载文件而不是打开
Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
Response.BinaryWrite(bytes);
Response.Flush();
Response.End();
}
}