Search code examples
c#stringcsvlinqline-by-line

Not able write list of values line by line in a csv file


Here i am reading a csv file line by line(to update and append some values) and convert into a list. While again trying to write a csv file from the list,I'm unable to write it line by line.

Actual Format:

1  abc 76-8 3 sht 09-9 5 bry 77-0

Expected Format:

 1 abc 76-8
 3 sht 09-9
 5 bry 77-0

Here is my code:

using (var reader = new StreamReader(@"D:FileWatcher/File_A.csv"))
{  
    List<string> fulllist = File.ReadAllLines(@"D:FileWatcher/File_A.csv").ToList();
    foreach(var item in fulllist)
    {
        var line = reader.ReadLine();
        var values = line.Split(',').ToList();
        var Col1Value = values[0].Substring(8,2);
        var Col0Value = values[0].Substring(0,7);

        values.RemoveAt(0);

        values.Insert(0, Col1Value);
        values.Insert(0, Col0Value);
        
        string combinedString = string.Join(",", values);

        var PathforFileB = @"D:FileWatcher/Result/File_B.csv";

        File.WriteAllText(PathforFileB, combinedString);
    }
}

Solution

  • The main problem in the original code is it re-opened the file at the beginning on every loop iteration. You can help a lot by changing File.WriteAllText() to File.AppendAllText() and including a line feed as part of the strings. But even then it was a lot less efficient and more complicated than it needed to be.

    var data = File.ReadLines(@"D:\FileWatcher\File_A.csv").
        Select(line => line.Split(',')).
        Select(line => $"{line[0].Substring(8,2)}, {line[0].Substring(0, 7)}, {string.Join(",", line.Skip(1))}");
    
    File.WriteAllLines(@"D:FileWatcher\Result\File_B.csv", data);