Skip to content

Instantly share code, notes, and snippets.

@BadgerCode
Created May 6, 2020 08:51
Show Gist options
  • Save BadgerCode/2e8b68a0ff899955dcd009950be6708a to your computer and use it in GitHub Desktop.
Save BadgerCode/2e8b68a0ff899955dcd009950be6708a to your computer and use it in GitHub Desktop.
Example of reading a CSV file in C# using the package CsvHelper
/* Install package CsvHelper */
public class Program
{
static async Task Main(string[] args)
{
var recipients = CSV.Read(@"C:\path\to\file.csv")
.Select(row =>
{
var name = row["Name"].ToString();
return new JObject
{
{ "Name", name }
};
})
.ToList();
}
}
public class CSV
{
public static List<Dictionary<string, string>> Read(string filename)
{
using var reader = new StreamReader(filename);
using var csv = new CsvReader(reader, CultureInfo.InvariantCulture);
return csv.GetRecords<dynamic>()
.Select(r => ((IDictionary<string, object>)r).ToDictionary(kvp => kvp.Key, kvp => kvp.Value?.ToString()))
.ToList();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment