I'm using CsvHelper. To write to a .csv file, I need a header based off of a class.
I write the header manually and it works, but I need to be done automatically when it is read.
All the documentation I can find says to use this expression, writer.WriteHeader<CSVDataFormat>(); but that isn't working because it needs more work done to it.
Here is the class that the header should be based off:
public class CSVDataFormat
{
public string FirstName { get; set; }
public string LastName { get; set; }
public float Wage { get; set; }
}
Here is the code for the reading and writing:
private void ReadCSV(string ogCsvFile)
{
using (var streamReaederfileDir = new StreamReader(@ogCsvFile))
{
using (var streamWriterFileDir = new StreamWriter(Path.Combine(Path.GetDirectoryName(ogCsvFile), "New" + Path.GetFileName(ogCsvFile))))
{
var reader = new CsvReader(streamReaederfileDir);
var writer = new CsvWriter(streamWriterFileDir);
writer.WriteHeader<CSVDataFormat>();
IEnumerable records = reader.GetRecords<CSVDataFormat>().ToList();
foreach (CSVDataFormat record in records)
{
record.Wage = record.Wage + (record.Wage / 10);
writer.WriteField(record.FirstName);
writer.WriteField(record.LastName);
writer.WriteField(record.Wage);
writer.NextRecord();
}
}
}
}
Update
This is the error I am getting when I run my code:
An unhandled exception of type 'CsvHelper.CsvMissingFieldException' occurred in CsvHelper.dll
Additional information: Fields 'FirstName' do not exist in the CSV file.
writer.WriteHeader<CSVDataFormat>();is meant to get the ` get & set ` funtions from the CSVDataFormat class and add their names and data types to the top of the CSV file. That header is required for CsvHelper."FirstName, LastName, Wage"not not going to write the values of those props)