4

Is it possible to write data at the end of the csv file or one line after the end of the csv file when using LINQToCSV library.

I am using LINQtoCSV and passing a List<> to write the data. my List<> is like

x    y    z

1    4    5

1    5    3

Now i want to do y*z for each record and write the sum at the end of the csv file.

Sum = 35

i Have been searching this for a while but didn't quite find any solution.

Maverick
  • 1,396
  • 5
  • 22
  • 42

2 Answers2

2

https://social.msdn.microsoft.com/Forums/vstudio/en-US/00c609c0-5048-4ef1-8c03-e7c6217d8a32/n-not-working-in-fileappendalltext?forum=csharpgeneral

File.AppendAllText(csvPath, ""); 

did the trick.

EDIT:

I looped through all the List records and collected the Sum of y*z.

sum = 0;
for (int i= 0; i < myList.Count; i++)
    sum += (y * z);

File.AppendAllText(csvPath, String.Concat("Sum = ", sum.ToString()));

For writing on one line after the end of the csv File, Environment.NewLine can be used

File.AppendAllText(csvPath, Environment.NewLine);
File.AppendAllText(csvPath, String.Concat("Sum = ", sum.ToString()));
Maverick
  • 1,396
  • 5
  • 22
  • 42
1

I don't know if this is what you're after, but I have used something like this in the past:

CsvContext csv = new CsvContext();
var models = csv.Read<CsvData>(@"c:\Icons\Windows7\Desktop\Book2.csv").ToList();
CsvData sum = new CsvData();
sum.z = models.Sum(m => m.y * m.z);
models.Add(sum);
csv.Write(models, @"c:\Icons\Windows7\Desktop\Book3.csv");

Where my model in this example was:

public class CsvData
{
    [CsvColumn(FieldIndex = 0)]
    public int x { get; set; }
    [CsvColumn(FieldIndex = 1)]
    public int y { get; set; }
    [CsvColumn(FieldIndex = 2)]
    public int z { get; set; }
}
Ric
  • 12,855
  • 3
  • 30
  • 36
  • Don't you hate it when you do all that work to contribute your time freely, and the person who asks the question doesn't even give you a +1 for your time? So, I did. –  Jul 25 '15 at 10:32
  • Haha yeah but what you gonna do! Thanks! – Ric Jul 25 '15 at 15:01