Csvhelper: Can we add new row into existing CSV file without header.

Created on 22 Aug 2018  路  4Comments  路  Source: JoshClose/CsvHelper

I want to append a record to an existing CSV file so the header is already available. I want to just append a new record into existing CVS file.

Following is my code.
string filePath = "C:\Users\dushyant.patel\Desktop\ExportUtility\123.csv";
StreamWriter writer = new StreamWriter(filePath, true);

SharedDataModel model = new SharedDataModel();
model.SrNo = "17";
model.TypeofEvidence = "Video";

var csv = new CsvWriter(writer);
var record = new List { model };
csv.WriteRecords(record);
writer.Close();
return View();

Most helpful comment

I have been able to append to a file without repeating the header row:

// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = !File.Exists(FileName)
};

// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        using (var csv = new CsvWriter(streamWriter, csvConfig))
        {
            // Append records to csv
            csv.WriteRecords(recordsToWrite);
        }
    }
}

_Note: make sure you build each record in the recordsToWrite collection the same way to avoid column mismatches_

All 4 comments

Is there any inbuilt method which I can use?

You would have to read the file then write it again. The reader and writer are forward only. There's no way to edit a file.

You can one file and write to another at the same time though, then delete the old file when done.

Ok. thanks for your valuable response

I have been able to append to a file without repeating the header row:

// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
    HasHeaderRecord = !File.Exists(FileName)
};

// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
    using (StreamWriter streamWriter = new StreamWriter(fileStream))
    {
        using (var csv = new CsvWriter(streamWriter, csvConfig))
        {
            // Append records to csv
            csv.WriteRecords(recordsToWrite);
        }
    }
}

_Note: make sure you build each record in the recordsToWrite collection the same way to avoid column mismatches_

Was this page helpful?
0 / 5 - 0 ratings