Write to new column of a csv file using Stringbuilder c#

Asked

Viewed 70 times

0

I saw an example of code right here in stackoverflow where I use the example below to write a CSV file using stringbuilder:

public void ExportarCsv(List<Result> erros)
        {
            string filename = "resultado.csv";
            string path = @"C:\Arquivo\";

            Console.WriteLine("Escrevendo no arquivo.");

            StringBuilder csvBuilder = new StringBuilder();

            //cria o header
            csvBuilder.AppendLine("Order;Motivo");

            foreach (var item in erros)
            {
                csvBuilder.AppendLine(item.CodigoPedido);
                
            }

            if (!Directory.Exists(path))
            {
                DirectoryInfo di = Directory.CreateDirectory(path);
            }

            File.WriteAllText(path + filename, csvBuilder.ToString(), Encoding.UTF8);
        }

In this example I have the heading Order and Reason, but I can only write below the Order. How do I write the values in each column respectively ?

1 answer

2


Simple... you’re doing this, you’re just not writing the rest of the content. Remembering that CSV is a file with delimiters, there are no columns... And in your case the separator is the default, ;.

Instead of concatenating your text to compose the line, I recommend using the interpolation feature indicated by the symbol $ before your string.

foreach (var item in erros)
{
    csvBuilder.AppendLine($"{item.CodigoPedido};{item.Motivo}");        
}
  • good thank you very much. Very simple, I was not able to see, thanks for the light kkkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.