Reading And Writing CSV Files In ASP.NET using C# (Using CsvHelper NuGet Package) 4

As I already mentioned in my older posts, NuGet Packages makes available ready to use tools and library for .NET application and saves our lot of time in coding to develop some specific functionality that are very common in most application development. CSV file Reading / Writing is one of them. CSV files are basically used for Data Restore/Backup or making communication between cross platform applications. 

Sample code is available for download at the bottom of this post

NuGet CsvHelper library is Extremely fast, flexible, reliable and easy to use in .NET applicaitons. It makes CSV file Reading / Writing a very easy task.

Before using CsvHelper library, we have to import it form NuGet Package Manager. Tools > Library Package Manager > Manage NuGet Package for Solution

Right after installation of CsvHelper, you can start coding.

First of all you have to include CsvHelper in your program by using statement.

 using CsvHelper; 

Now we will have an example  csv file.(test.csv)

In test.csv file we have three fields seperated by comma(,) as Name,Sex,Occupation


Name,Sex,Occupation
Rohan,M,Developer
Jack,M,Writer
Ash,F,Actor

Now suppose we want to read this test.csv file into our program. Following is the code for reading CSV file.

Reading CSV file


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CsvHelper;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
 string output;
 protected void Page_Load(object sender, EventArgs e)
 {
 //Stream reader will read test.csv file in current folder
 StreamReader sr = new StreamReader(Server.MapPath(@"test.csv"));
 //Csv reader reads the stream
 CsvReader csvread = new CsvReader(sr);

//csvread will fetch all record in one go to the IEnumerable object record
 IEnumerable<TestRecord> record = csvread.GetRecords<TestRecord>();

 foreach (var rec in record) // Each record will be fetched and printed on the screen
 {
 Response.Write(string.Format("Name : {0}, Sex : {1}, Occupation : {2} <br/>", rec.name, rec.sex, rec.occupation));
 }
 sr.Close();
 }
}

public class TestRecord // Test record class
{
 public string name { get; set; }
 public string sex { get; set; }
 public string occupation { get; set; }
}

As you can see in the code, there is a class TestRecord, that holds the data. Its property name should be same as in the csv file.

Output:

Name : Rohan, Sex : M, Occupation : Developer
Name : Jack, Sex : M, Occupation : Writer
Name : Ash, Sex : F, Occupation : Actor

Now as we have seen that there is just one line IEnumerable<TestRecord> record = csvread.GetRecords<TestRecord>(); that fetch all csv data in one go to an IEnumerable object.

Writing a CSV file

For simplicity I have modified the earlier code for both Reading and Writing to the csv file. Same loop is used for reading csv data from one file and writes the same data to another csv file.

Refer the code.


using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using CsvHelper;
using System.IO;
public partial class _Default : System.Web.UI.Page
{
 string output;
 protected void Page_Load(object sender, EventArgs e)
 {
 //Stream reader will read test.csv file in current folder
 StreamReader sr = new StreamReader(Server.MapPath(@"test.csv"));
 //For easy understanding we will be writing same csv data read from one test.csv file to another copyfile.csv file
 StreamWriter write = new StreamWriter(Server.MapPath(@"copyfile.csv"));

 //Csv reader reads the stream
 CsvReader csvread = new CsvReader(sr);

 //Csv writer stream
 CsvWriter csw = new CsvWriter(write);

 //csvread will fetch all record in one go to the IEnumerable object record
 IEnumerable<TestRecord> record = csvread.GetRecords<TestRecord>();

foreach (var rec in record) // Each record will be fetched and printed on the screen
 {
 //reads csv and print output
 Response.Write(string.Format("Name : {0}, Sex : {1}, Occupation : {2} <br/>", rec.name, rec.sex, rec.occupation));
 //same time writes the csv file to another file : copyfile.csv
 csw.WriteRecord<TestRecord>(rec);
 }
 sr.Close();
 write.Close();//close file streams
 }
}

public class TestRecord // Test record class
{
 public string name { get; set; }
 public string sex { get; set; }
 public string occupation { get; set; }
}

You can download sample code below:

Click here to download Sample working code for CsvHelper

4 thoughts on “Reading And Writing CSV Files In ASP.NET using C# (Using CsvHelper NuGet Package)

  1. Reply mrugeshbapotra Mar 19,2013 5:17 PM

    This is really very useful tutorial….

  2. Reply Tiju Jul 17,2013 5:30 PM

    does it takes care of ‘,’ in the data ?

  3. Reply Leonardo Aug 9,2013 6:36 PM

    very good the post, very interesting.

Leave a Reply