gpt4 book ai didi

c# - 将数据从 SQL Server 导出到 C# 中的文本文件(保存到特定文件夹)

转载 作者:行者123 更新时间:2023-12-02 04:14:13 24 4
gpt4 key购买 nike

数据将首先提取到数据表中,然后数据表将导出到可以在记事本中查看的文本文件。

但是,我不知道如何使代码能够将工作保存到特定文件夹

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com