I have a query which give more then 500 rows and I have ordered them according to specific column say Name, and I am writing the result in a text file. I want to add a break record after last row of each group. For example my query result is:
Name Address City State Zip Phone Break
AAA BBB CCC SS 1234 555
AAA DDD EEE SS 1234 666
MMM YYY ZZZ EE 4457 999
LLL DDD ooo WW 7895 777
But I want to add an extra line and add "Yes" as Break value in text file as:
Name Address City State Zip Phone Break
AAA BBB CCC SS 1234 555
AAA DDD EEE SS 1234 666
YES
MMM YYY ZZZ EE 4457 999
YES
LLL DDD ooo WW 7895 777
YES
My code is:
string query = " select * from table order by name";
SqlDataReader reader;
string connStr = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;
string strDelimiter = "\t";
string strDel = "\"";
string strFilePath = @"C:\" TextFile_" + DateTime.Now.ToString("yyyyMMdd") + ".txt";
StringBuilder sb = new StringBuilder();
using (SqlConnection conn = new SqlConnection(connStr))
{
conn.Open();
using (reader = new SqlCommand(query, conn).ExecuteReader())
{
for (int i = 0; i < reader.FieldCount; i++)
{
sb.Append(strDel);
sb.Append(reader.GetName(i));
sb.Append(strDel);
if (i == reader.FieldCount - 1)
{
continue;
}
sb.Append(strDelimiter);
}
sb.Append(Environment.NewLine);
if (reader.HasRows)
{
Object[] items = new Object[reader.FieldCount];
while (reader.Read())
{
reader.GetValues(items);
for (int i = 0; i < reader.FieldCount; i++)
{
sb.Append(strDel);
sb.Append(reader.GetValue(i).ToString());
sb.Append(strDel);
if (i == reader.FieldCount - 1)
{
continue;
}
sb.Append(strDelimiter);
}
sb.Append(Environment.NewLine);
}
}
}
conn.Close();
File.WriteAllText(strFilePath, sb.ToString());
}