Search code examples
c#stringstreamreader

Rearrange csv.file


I want to rearrange my Text file. Here is my data of my Text File as below

11;12;13;14;15;

1;2;3;4;5;

I want arrange it become as below

11=1

12=2

13=3

14=4

15=5

error message = The file could not be read: Index was outside the bounds of the array.

///////////////////////////////////////////////////////////


Solution

  • I believe you have already read file using File.ReadAllLines() method. it stores each line as a single element of the list. Now to transform ; separated line to the given format you can try below code,

    var lines = File.ReadAllLines(<csv file path>);
    var firstLine = lines[0].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
    var secondLine = lines[1].Split(new string[] { ";" }, StringSplitOptions.RemoveEmptyEntries);
    var listLength = Math.Min(firstLine.Lenght, secondLine.Length);
    for(var i = 0; i < listLength; i++)
        Console.WriteLine($"{firstLine[i]}={secondLine[i]}"); //Instead of console print you can store it in CSV