Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I append CSV using CSV helper?

Tags:

c#

csvhelper

I went through documentation and I didn't see anything for it. I'm using the same exact write function from documentation but the problem is I also need to append. So far I've tried reading it than adding the CSV into a list than I write the list to CSV. Is there a better way I could append?

The exact write function I use with my own variables

var records = new List<Foo>
{
    new Foo { Id = 1, Name = "one" },
};

using (var writer = new StreamWriter("path\\to\\file.csv"))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
    csv.WriteRecords(records);
}

What I use to read but with my own variables:

using (var reader = new StreamReader("path\\to\\file.csv"))
using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
{
    var records = csv.GetRecords<Foo>();
}

Hopefully someone can help!

like image 608
asds dsadsasd Avatar asked Sep 20 '25 17:09

asds dsadsasd


1 Answers

Use the StreamWriter(String, Boolean) constructor to specify you want to append to an existing file:

Initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, this constructor creates a new file.

Parameters

path

String

The complete file path to write to.

append

Boolean

true to append data to the file; false to overwrite the file. If the specified file does not exist, this parameter has no effect, and the constructor creates a new file.

As for your CsvHelper CsvWriter, you need to configure it to omit the header depending on if you are appending or creating:

bool append = true;
var config = new CsvConfiguration(CultureInfo.InvariantCulture);
config.HasHeaderRecord = !append;

using (var writer = new StreamWriter("path\\to\\file.csv", append))
{
    using (var csv = new CsvWriter(writer, config))
    {
        csv.WriteRecords(records);
    }
}
like image 192
Filburt Avatar answered Sep 22 '25 05:09

Filburt