将数据从 SQL 服务器导出到 C# 中的文本文件(保存到特定文件夹)

Export data from SQL Server to Text file in C# (Saving to a specific folder)

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

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

P.S.I 也想给文件起一个动态名称(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$...%'(不带“'”)

数据由 $.

分隔

我终于做到了:

StreamWriter file = new StreamWriter(@"C:\test");
                        file.WriteLine(txt.ToString());
                        file.Close();

改为使用响应。 , 这很有魅力。

    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();
    }