将数据从SQL Server导出到C#中的文本文件(保存到特定文件夹) [英] Export data from SQL Server to Text file in C# (Saving to a specific folder)
本文介绍了将数据从SQL Server导出到C#中的文本文件(保存到特定文件夹)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
首先将数据提取到数据表中,然后将数据表导出到可以在记事本中查看的文本文件中.
The data will be first fetched into a DataTable and then the DataTable will be exported to a Text file which can be viewed in Notepad.
但是,我不知道如何使代码正常工作,以将工作保存到特定文件夹中
But, i dont know how to make the code work for save the work to a specific folder
P.S.我也想给该文件一个动态名称(YEARmonthDAYhour.txt)
P.S.I want to give to the file a dynamic name too (YEARmonthDAYhour.txt)
到目前为止,这是我的代码:
this is my code so far:
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 $ ...%'(不带'")
'#InfofromSQL$InfofromSQl$InfofromSQL$...%' (without " ' ")
数据用 $ 分隔.
推荐答案
我终于做到了:
StreamWriter file = new StreamWriter(@"C:\test");
file.WriteLine(txt.ToString());
file.Close();
代替使用响应.,这就像一种魅力.
Instead using response. , this works like a charm.
这篇关于将数据从SQL Server导出到C#中的文本文件(保存到特定文件夹)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文