Page cover

CSV

Read

Perigee ships with several powerful CSV tools that make reading even complicated CSV's very easy and fast with memory efficient span based data reads.

//Get a memory stream to the file
using MemoryStream ms = new MemoryStream(File.ReadAllBytes("Products.csv"));

//Read the CSV as a list of T classes
List<Product> products = CSVReader.ReadAs<Product>(ms);

//Read the csv as a DataTable
DataTable ProductTable =  CSVReader.ToDataTable(ms, out var res);

When using the .ToDataTable() methods, you get the resulting parse parameters sent back as an out variable. This allows you to check it's encoding, formatting, delimiters, header row location, etc.

Write

To write CSV data supply a DataTable and any additional handlers to override specifics on a data type.

  • We'll read in the Products.CSV as our source.

  • Let's then declare a writer, and set it to BAR delimited

  • Register a decimal handler that write's any decimals with 3 digits after the period

    • The handler sends you back the object (in this case a decimal)

    • The Row Index.

    • The Column Name.

    • It expects a return value of the string converted version, as well as a boolean indicating if the transform was successful.

    • Any NON-SUCCESSFUL transformed handlers are added to the writers LoadLog property and can be viewed after conversion.

  • Then simply call .Write().

Clean

Maybe the only thing you need to do is take the absolutely horrendous CSV data in the Sample Data section and just create a CSV that can be cleanly loaded into another system.

This transforms the very badly formatted CSV Sample Data into this:

Sample Data

Included is the sample data and classes used above.

Last updated