0

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);
    }
}
Tim Schmelter
  • 450,073
  • 74
  • 686
  • 939
shreyas
  • 69
  • 6
  • The line string in the example has its words separated by a space not by a comma. Why do you split it using the comma as separator? By the way, what is the difference between the actual value and the expected value? – Steve Dec 15 '22 at 11:08
  • `File.ReadAllLines` reads already all lines into a collection(`string[]`), there is no need to create a new collection(`List`) afterwards just to loop it with a `foreach`, thats just a waste of CPU and memory. – Tim Schmelter Dec 15 '22 at 11:08
  • @TimSchmelter but still not able to write the items line by line – shreyas Dec 15 '22 at 11:18
  • you need an end of line `\n` or `\r\n` character at the end of each line. – mcy Dec 15 '22 at 11:36

1 Answers1

2

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);
Joel Coehoorn
  • 399,467
  • 113
  • 570
  • 794