将数据从 SQL Server 导出到 C# 中的文本文件(保存到特定文件夹)
本文关键字:文件 文本 保存 文件夹 SQL 数据 Server | 更新日期: 2023-09-27 18:30:58
数据
将首先被提取到DataTable中,然后将DataTable导出到可以在记事本中查看的文本文件中。
但是,我不知道如何使代码用于将工作保存到特定文件夹
附言我也想给文件一个动态名称(YEARmonthDAYhour.txt)
这是我到目前为止的代码:
protected void ExportTextFile(object sender, EventArgs e)
{
string constr = ConfigurationManager.ConnectionStrings["ConnectionString2"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("Select * from details"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
string txt = string.Empty;
txt += "#";
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn column in dt.Columns)
{
txt += row[column.ColumnName].ToString() + "$";
}
}
txt += "%";
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=AAAAMM-aaaammddhhmmss.txt");
Response.Charset = "";
Response.ContentType = "application/text";
Response.Output.Write(txt);
Response.Flush();
Response.End();
}
}
}
}
}
预期输出:
'#InfofromSQL$InfofromSQl$InfofromSQL$...%' (不带 "' ")
以 $ 分隔的数据。
static string connString = @"Server=myServerName;Database=myDbName;Trusted_Connection=True;";
static string fileName = @"C:'CODE'myfile.txt";
public static void WriteFile(string fileName)
{
SqlCommand comm = new SqlCommand();
comm.Connection = new SqlConnection(connString);
String sql = @"select col1, col2 from myTable";
comm.CommandText = sql;
comm.Connection.Open();
SqlDataReader sqlReader = comm.ExecuteReader();
// Change the Encoding to what you need here (UTF8, Unicode, etc)
using (System.IO.StreamWriter writer = new System.IO.StreamWriter(fileName, false, Encoding.UTF8))
{
while (sqlReader.Read())
{
writer.WriteLine(sqlReader["col1"] + "'t" + sqlReader["col2"]);
}
}
sqlReader.Close();
comm.Connection.Close();
}
我终于做到了:
StreamWriter file = new StreamWriter(@"C:'test");
file.WriteLine(txt.ToString());
file.Close();
而是使用响应,这就像一个魅力。