C# code to convert a data reader to stringbuilder

Rajnilari2015
Posted by Rajnilari2015 under C# category on | Points: 40 | Views : 266
The below code will do so

public static StringBuilder ConvertDataReaderToStringBuilder(string sqlConnectionString, string storedprocedureName)
{
StringBuilder sb = new StringBuilder();
try
{
using (var sqlCon = new SqlConnection(sqlConnectionString))
{

using (SqlCommand cmd = new SqlCommand(storedprocedureName, sqlCon))
{
cmd.CommandType = CommandType.StoredProcedure;

sqlCon.Open();

using (SqlDataReader reader = cmd.ExecuteReader())
{
//Get All column
var columnNames = Enumerable.Range(0, reader.FieldCount)
.Select(reader.GetName)
.ToList();

//Create headers
sb.Append(string.Join(",", columnNames));

//Append Line
sb.AppendLine();

while (reader.Read())
{
for (int i = 0; i < reader.FieldCount; i++)
{
string value = reader[i].ToString();
if (value.Contains(","))
value = "\"" + value + "\"";

sb.Append(value.Replace(Environment.NewLine, " ") + ",");
}
sb.Length--; // Remove the last comma
sb.AppendLine();
}
}
}
}

}
catch (Exception ex)
{
throw ex;
}
return sb;
}

Comments or Responses

Login to post response