1

I have a CSV file like this:

Header1;Header2;Header3;Header4;Header5;Header6
abc;123;xyz;...;...;...

I would like to add a new column at the end of this csv and directly merge column 1+2 in this new column:

Header1;Header2;Header3;Header4;Header5;Header6;Header7
abc;123;xyz;...;...;...;abc123

I was able to add a new column but how to add the data?

Here is what I'm using:

static void Main(string[] args)
{
    String filePath = @"C:/Data.csv";

    var csv = File.ReadLines(filePath)
      .Select((line, index) => index == 0
         ? line + ";ExtID"
         : line + ";" + line.ToString())
      .ToList();

    File.WriteAllLines(filePath, csv);
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    Personally, I would _never ever_ dare to do my own CSV parsing. Using one of the many [CSV reading libraries](https://stackoverflow.com/q/1941392/107625) should be the way to go. – Uwe Keim Dec 05 '19 at 09:01

2 Answers2

1

If you have a simple csv (without quotations) you can try Linq: either add caption or Split line and Concat 2 items Taken from it:

  ...

  var csv = File
    .ReadLines(filePath)
    .Select((line, index) => index == 0 
       ? line + ";ExtID"                                     // Extra header
       : line + ";" + string.Concat(line.Split(';').Take(2)) // first two items added
     )
    .ToList();

  File.WriteAllLines(filePath, csv);
Dmitry Bychenko
  • 180,369
  • 20
  • 160
  • 215
0

A no LINQ approach

        string filePath = @"C:/Data.csv";
        var lines = File.ReadLines(filePath).ToList();

        // Add new Column
        var newColumn = ";Header7";
        lines[0] = lines[0] += newColumn;

        // Adds items to the new column
        for (int index = 1; index < lines.Count; index++)
        {
            var rowItems = lines[index].Split(';');
            lines[index] = $"{lines[index]};{rowItems[0]}{rowItems[1]}";
        }

        File.WriteAllLines(filePath, lines);
Ndubuisi Jr
  • 461
  • 6
  • 13