我想获取此表的所有列和行并保存在.txt文件中。
文本文件名必须是SubscriberID.txt(例如:281063.txt或281064.txt)并保存在文件夹名称manoj中。
在281063.txt文件中,数据保存在SubscriberID:60; npercentscore:60; nevaleid:7091,courseID:1,... 就像这样。
Here i take all the data to a datatable:
string query = "SELECT * FROM DATAFETCH";
SqlCommand cmd = new SqlCommand(query, conn);
DataTable dt = new DataTable();
dt.Load(cmd.ExecuteReader());
如何使用c#asp .net实现目标? 任何建议??
答案 0 :(得分:0)
如果每行需要一个文件,可以这样做:
foreach (DataRow dr in dt.Rows)
{
StreamWriter sw = new StreamWriter(PathToStoreTheFile + dr["SubscriberID"].ToString() + ".txt"); //create the file
string line = "SubscriberID:" + dr["SubscriberID"].ToString() + ";";
line += "npercentscore:" + dr["npercentscore"].ToString() + ";";
line += "nevaleid:" + dr["nevaleid"].ToString() + ";";
line += "courseID:" + dr["courseID"].ToString() + ";";
//and so on
sw.WriteLine(line); //write data
sw.Close();
}
或者您也可以遍历列:
foreach (DataRow dr in dt.Rows)
{
StreamWriter sw = new StreamWriter(PathToStoreTheFile + dr["SubscriberID"].ToString() + ".txt");
string line = "";
foreach (DataColumn dc in dt.Columns)
{
line += dc.ColumnName + ":" + dr[dc].ToString() + ";";
}
sw.WriteLine(line);
sw.Close();
}