Thursday, December 30, 2021

CSV Helper

 

CsvHelper:

A .NET library for reading and writing CSV files. Extremely fast, flexible, and easy to use.


Github:
https://joshclose.github.io/CsvHelper/


Reading a csv file :

public class Foo { [Name("id")] public int Id { get; set; } [Name("name")] public string Name { get; set; } }

using (var reader = new StreamReader(@"c:\projects\data.csv")) using (var csv = new CsvReader(reader, config)) { var records = csv.GetRecords<Foo>(); }

Writing to CSV:

using (var writer = new StreamWriter("c:\projects\data.csv")
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture)) { csv.WriteRecords(records); }


Utility method for refactoring code for getting all the records from CSV:

private IEnumerable<T> ReadStream<T, TMap>(string csvPath) where TMap: ClassMap { IEnumerable<T> records; using (var reader = new StreamReader(this.awsS3Service.GetS3BucketFile(csvPath))) { using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture)) { csv.Configuration.Delimiter = "|"; csv.Configuration.RegisterClassMap<TMap>(); records = csv.GetRecords<T>().ToList(); } } return records; }


Call above method using :
this.ReadStream<BrandFile, BrandFileCSVMap>(s3FilePath)

public class BrandFile { public int BrandId { get; set; } public string BrandName { get; set; } public string BrandWebsite { get; set; } public string BrandLogoURL { get; set; } }

public sealed class BrandFileCSVMap: ClassMap<BrandFile> { public BrandFileCSVMap() { AutoMap(CultureInfo.InvariantCulture); } }