How To Read And Write CSV File In C#

In this article, we will learn how to read and write CSV files In C#.

Getting Started

The CsvHelper is a .NET library for reading and writing CSV files. Extremely fast, flexible, and easy to use.

Install CsvHelper, to install this you need to execute below command in Package Manager Console or find CsvHelper in Nuget-Solution.

Package Manager Console

PM> Install-Package CsvHelper

.NET CLI Console

> dotnet add package CsvHelper

Reading a CSV File

Let’s say we have a CSV file that looks like this.

Book1.csv

Now, let’s add a new Book.cs class file in the Models folder.

What if we don’t have control over the class we want to map to so we can’t add attributes to it? In this case, we can use a fluent ClassMap to do the mapping.

using CsvHelper.Configuration;

namespace Read_Write_CSV.Models
{
    public class Book
    {
        public string ID { get; set; }
        public string BookName { get; set; }
        public string AuthorName { get; set; }
    }
    public class BookMap : ClassMap<Book>
    {
        public BookMap()
        {
            Map(l => l.ID).Name("ID");
            Map(l => l.BookName).Name("Book Name");
            Map(l => l.AuthorName).Name("Author Name");
        }
    }
}

Open the Program.cs file and add the code in it.

using CsvHelper;
using Read_Write_CSV.Models;
using System.IO;
using System.Linq;

namespace Read_Write_CSV
{
    class Program
    {
        static string filePath = @"D:\Yasin_Projects\Code Hubs\.NET Core\Read-Write CSV\Read-Write CSV\CSV\";
        static void Main(string[] args)
        {
            Read(Path.Combine(filePath, "Book1.csv"));
        }
        static void Read(string fileName)
        {
            FileInfo inputFile = new FileInfo(fileName);
            using (var reader = new StreamReader(inputFile.FullName))
            using (var csvReader = new CsvReader(reader, System.Globalization.CultureInfo.CurrentCulture))
            {
                csvReader.Configuration.RegisterClassMap<BookMap>();
                var bookList = csvReader.GetRecords<Book>().ToList();
            }
        }
    }
}

Output:

 

Writing a CSV File

Now let’s look at how we can write CSV files. It’s basically the same thing but in reverse order.

Let’s use the same class definition as before (Book.cs).

 

Open the Program.cs file and add the code in it.

using CsvHelper;
using Read_Write_CSV.Models;
using System.Collections.Generic;
using System.IO;
using System.Linq;

namespace Read_Write_CSV
{
    class Program
    {
        static string filePath = @"D:\Yasin_Projects\Code Hubs\.NET Core\Read-Write CSV\Read-Write CSV\CSV\";
        static void Main(string[] args)
        {
            Read(Path.Combine(filePath, "Book1.csv"));
        }
        static void Read(string fileName)
        {
            FileInfo inputFile = new FileInfo(fileName);
            using (var reader = new StreamReader(inputFile.FullName))
            using (var csvReader = new CsvReader(reader, System.Globalization.CultureInfo.CurrentCulture))
            {
                csvReader.Configuration.RegisterClassMap<BookMap>();
                var bookList = csvReader.GetRecords<Book>().ToList();
                var filteredBookList = bookList.Where(x => !x.BookName.Contains("Test") || !x.AuthorName.Contains("Test")).ToList();
                WriteFile(filteredBookList, inputFile.Name);
            }
        }
        static void WriteFile(List<Book> data, string fileName)
        {
            string path = Path.Combine(filePath, "Filtered");
            //Create a directory if it doesn't exist
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            path = Path.Combine(path, fileName);
            FileInfo toFile = new FileInfo(path);
            using (var writer = new StreamWriter(toFile.FullName))
            using (var csvWriter = new CsvWriter(writer, System.Globalization.CultureInfo.CurrentCulture))
            {
                csvWriter.Configuration.RegisterClassMap<BookMap>();
                csvWriter.WriteRecords(data);
            }
        }
    }
}

In the above example, we first read the CSV file and create a list. Then we apply a filter on that list and pass that filtered data to the WriteFile method.

Output:

 

 

Please give your valuable feedback and if you have any questions or issues about this article, please let me know.

Also, check The == Operator VS .Equals() Method In C#

2 Comments

  1. Sani

    This is just another great contribution. Thanks Yasin.

    0
    0
    Reply
    1. You’re welcome Sani 🙂

      0
      0
      Reply

Submit a Comment

Your email address will not be published. Required fields are marked *

Subscribe

Select Categories