Created
May 6, 2020 08:51
-
-
Save BadgerCode/2e8b68a0ff899955dcd009950be6708a to your computer and use it in GitHub Desktop.
Example of reading a CSV file in C# using the package CsvHelper
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* 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