Reputation: 231
I have a datatable
and exporting row wise data to text file
foreach (DataRow dr in dt1.Tables[0].Rows)
{
WriteToFile("Docket with Docket number {0} and Request ID {1} booked from Agent Account having Login ID {2} on {3}"+ dr["DOCKET_NUMBER"].ToString()+
dr["REQUEST_ID"].ToString()+ dr["CREATED_BY"].ToString()+dr["CREATE_DATE"].ToString());
}
private static void WriteToFile(string text)
{
string path = "E:\\ServiceLog.txt";
using (StreamWriter writer = new StreamWriter(path, true))
{
writer.WriteLine(string.Format(DateTime.Now.ToString("dd/MM/yyyy hh:mm:ss tt")+ " "+ text));
// writer.WriteLine(string.Format(text +));
writer.Close();
}
}
}
can i export whole datatable
to text file at once??
Upvotes: 1
Views: 3737
Reputation: 109
i've never write Datatable into txt file, but i would suggest you to try ClosedXml and write Datatable into csv file at once. ClosedXml is one great library and i've no problem running it on production so far, you should check out their github page on how to use it and or extend it.
Upvotes: 0
Reputation: 14231
What about writing to xml? Xml is a text, so the condition is met.
Use DataTable.WriteXml method for writing and DataTable.ReadXml method for reading data to/from text file.
Upvotes: 1
Reputation: 9606
You could do this..
var lines = dt1.Tables[0].AsEnumerable().Select(dr => "Docket with Docket number {0} and Request ID {1} booked from Agent Account having Login ID {2} on {3}" + dr["DOCKET_NUMBER"].ToString() +
dr["REQUEST_ID"].ToString() + dr["CREATED_BY"].ToString() + dr["CREATE_DATE"].ToString());
File.WriteAllLines("YourFilePath",lines);
Upvotes: 1
Reputation: 133403
You can use StringBuilder class and its methods i.e. AppendFormat
and AppendLine
to read all rows. then afterwards just invoke you method WriteToFile
StringBuilder sb = new StringBuilder();
foreach (DataRow dr in dt1.Tables[0].Rows)
{
sb.AppendFormat("Docket with Docket number {0} and Request ID {1} booked from Agent Account having Login ID {2} on {3}", dr["DOCKET_NUMBER"].ToString(), dr["REQUEST_ID"].ToString(), dr["CREATED_BY"].ToString(), dr["CREATE_DATE"].ToString());
sb.AppendLine();
}
WriteToFile(sb);
Upvotes: 2