Reputation: 245
I am using the library CSV Helper found at https://joshclose.github.io/CsvHelper/ to try and write a function that will export a class for me. Here is my example class:
public class Z1000
{
public string ModelNumber { get; set; }
public string SerialNumber { get; set; }
private string InputVolts { get; set; }
private string InputHz { get; set; }
private string InputPhase { get; set; }
private string InputAmps { get; set; }
private string OutputVolts { get; set; }
private string OutputHz { get; set; }
private string OutputPhase { get; set; }
private string OutputAmps { get; set; }
private string Type { get; set; }
private string WiringDiagram { get; set; }
private string SCCR { get; set; }
private string FLA { get; set; }
private bool SuitableForUseAsServiceEquipment { get; set; } = false;
private List<string> InstanceManuals { get; set; } = new List<string>();
private List<string> Options { get; set; } = new List<string>();
private List<Fuse> Fuses { get; set; } = new List<Fuse>();
}
This class has several functions as well, I excluded them as they are not important to the question. Here is the function I am trying to use to export a single record.
public void ExportToCsv<T>(T classToExport)
{
using (StreamWriter writer = new StreamWriter(@"C:\Data\Output.csv"))
{
var csv = new CsvWriter(writer);
csv.WriteHeader(typeof(T));
csv.WriteRecord(classToExport);
}
}
The code executes just fine but for some reason the csv file that gets exported is just empty. Am I missing some kind of step here? I have tried it several different ways and just can't seem to lock it down. I read the documentation for writing and their examples and none of it seems to work for me. Am I missing something entirely?
EDIT:
I put a break point and verified the public member data is being written.
Upvotes: 1
Views: 2670
Reputation: 6164
It appears that this library requires you to flush a record after outputting it.
From the GitHub site: https://joshclose.github.io/CsvHelper/writing
Ending the Row
When you are done writing the row, you need to flush the fields and start a new row. Flushing and starting a new row are separated so that you can flush without creating a new row. Calling
NextRecord()
will flush for you.
Upvotes: 2