数据将首先提取到数据表中,然后数据表将导出到可以在记事本中查看的文本文件。
但是,我不知道如何使代码能够将工作保存到特定文件夹
P.S.我也想给该文件一个动态名称(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();
}
关于c# - 将数据从 SQL Server 导出到 C# 中的文本文件(保存到特定文件夹),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34851800/