C# CSV Parsing Complete Example

In this example, we are going to read simple price records from a CSV file and store them in the database. The program is supposed to run on schedule by an OS, such as Cron or Task Scheduler. The basic structure of our project is as follows:

  • domain
    • PriceCsvRecord.cs
  • options
    • CsvOptions.cs
    • DbOptions.cs
  • repositories
    • PriceRepository.cs
  • services
    • CsvParsingService.cs
    • PriceService.cs
  • CsvJob.cs
  • Program.cs
  • appsettings.json

The structure follows a common Domain-Driven Design (DDD) approach, and we will see the purpose of each file later, but here is the workflow in a nutshell:

  1. Program.cs is the entry point of the program, that will do the dependency injection and start the CSV parsing job.
  2. CsvJob starts the service and call the CSV processing routine, handling errors if necessary.
  3. PriceService does CSV parsing by calling CsvParsingService, converts CSV records to the domain objects and stores relevant data to the database via PriceRepository.