Converting store procedure data to a csv. I am trying to figure out how to use the commas and quotations for the fields that are empty

sb.AppendLine("Employee Id,First Name,Last Name,Email,Username,Password,Role,Group Name,Country Code, Supervisor Id, Hire Date, Birth Date");

for (int i = 0; i < dt.Rows.Count; i++)
{
    String[] empid = dt.Rows[i]["EmpId"].ToString().Split(new Char[] { '-' });
    sb.AppendLine(Convert.ToInt32(empid[0]).ToString("000000") + "," + dt.Rows[i]["FirstName"] + "," + dt.Rows[i]["LastName"].ToString().Replace(",", " ") +
         ",," + dt.Rows[i]["Email"] + ",reward," + dt.Rows[i]["Role"] + ",CCCC," + ",," + ",," + dt.Rows[i]["EmployeeHireDate"] + "," + dt.Rows[i]["EmployeeBirthDate"]);
}

email field needs to be empty,
username needs to be the email,
country code needs to be empty,
supervisor id needs to be empty,

>Solution :

Replace this segement:

+ ",CCCC," + ",," + ",," +

with this:

+ ",CCCC,,," + 

But you’ll really do MUCH better with a dedicated csv library, of which there are several good options on NuGet.

Additionally, if you’re using StringBuilder because you heard it’s faster, remember that faster is relative. StringBuilder is faster than string concatenation for this kind of work, but if you’re ultimately going to writing to a network stream, file, or web response you’ll do even better using a StreamWriter

Leave a Reply