C# / .NETSecurityDevOps
C# / .NET
C# CSV files
Alexandru Puiu
Alexandru Puiu
September 16, 2012
1 min

This NuGet package called CSVHelper lets you create an object representation of a CSV file, to read and write CSV files with ease, and use linq on them.

You first need to get CsvHelper from NuGet Add a reference to the libraries you got

using CsvHelper;
using CsvHelper.Configuration;

Create a Model to match the CSV file. You can reference columns by Index or Name (You can only reference by name if the CSV file contains a header)

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsvHelper.Configuration;
namespace Models
{
    class InputCSVModel
    {
        [CsvField(Index = 0)]
        public string A { get; set; }
        [CsvField(Index = 1)]
        public DateTime B { get; set; }
        [CsvField(Index = 2)]
        public string C { get; set; }
    }
}

Next, we read in the CSV file

CsvConfiguration conf = new CsvConfiguration();
conf.AllowComments = false;
conf.HasHeaderRecord = false;
List list = null;
StreamReader streamReader = new StreamReader(inputFilePath);
CsvReader csvReader = new CsvReader(streamReader, conf);
list = csvReader.GetRecords().ToList();
streamReader.Close();
streamReader.Dispose();

At this point the entire CSV file is read in and available as a List of InputCSVModel.


Tags

utils
Alexandru Puiu

Alexandru Puiu

Engineer / Security Architect

Systems Engineering advocate, Software Engineer, Security Architect / Researcher, SQL/NoSQL DBA, and Certified Scrum Master with a passion for Distributed Systems, AI and IoT..

Expertise

.NET
RavenDB
Kubernetes

Social Media

githubtwitterwebsite

Related Posts

Uploading Large Files
Upload Large Files in C#
September 21, 2020
4 min
© 2022, All Rights Reserved.

Quick Links

Get In TouchAbout Me

Social Media