问题
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.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();
}
}
}
}
}
expected output:
'#InfofromSQL$InfofromSQl$InfofromSQL$...%' (without " ' ")
data separated by $.
回答1:
I did it finally:
StreamWriter file = new StreamWriter(@"C:\test");
file.WriteLine(txt.ToString());
file.Close();
Instead using response. , this works like a charm.
回答2:
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();
}
来源:https://stackoverflow.com/questions/34851800/export-data-from-sql-server-to-text-file-in-c-sharp-saving-to-a-specific-folder