Helper methods that deal with CSV exporting using CsvHelper.
$ dotnet add package CommonNetFuncs.CsvThis project contains helper methods for reading and writing CSV files.
Helpers for exporting data to a CSV file.
Export data from an IEnumerable or DataTable
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
Person[] testData = [ new() { Name = "Chris", Age = 32 }, new() { Name = "Nick", Age = 43 } ];
await using MemoryStream ms = new();
await testData.ExportToCsv(ms); // ms contains CSV data for testData
Helpers for ingesting data from CSV files.
Read CSV data directly from a physical CSV file or stream containing its data into a List. CSV data should match the type of T.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> csvPeople = CsvReadHelpers.ReadCsv(@"C:\Documents\People.csv"); // csvPeople contains list of values from People.csv
Asynchronously read CSV data directly from a physical CSV file or stream containing its data into a List. CSV data should match the type of T.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> csvPeople = await CsvReadHelpers.ReadCsvAsync(@"C:\Documents\People.csv"); // csvPeople contains list of values from People.csv
Asynchronously read CSV data directly from a physical CSV file or stream containing its data into an IAsyncEnumerable. CSV data should match the type of T.
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
List<Person> result = new();
await foreach (Person record in CsvReadHelpers.ReadCsvAsyncEnumerable<Person>(@"C:\Documents\People.csv"))
{
result.Add(record);
}
// Result contains list of all records within People.csv
Read CSV data directly from a physical CSV file or stream containing its data into a DataTable. DataTable can be constructed with a definite or indefinite type
public class Person
{
public string Name { get; set; }
public int Age { get; set; }
}
using DataTable dataTable = CsvReadHelpers.ReadCsvToDataTable(@"C:\Documents\People.csv"); // Indeterminate type in People.csv, dataTable contains all records from People.csv with all values as strings
using DataTable dataTable = CsvReadHelpers.ReadCsvToDataTable(@"C:\Documents\People.csv", typeof(Person)); // Known type in People.csv, dataTable contains all records from People.csv with all values typed per Person class
Install via NuGet:
dotnet add package CommonNetFuncs.Csv
This project is licensed under the MIT License - see the LICENSE file for details.