Wednesday, October 21, 2015

Read data from a CSV file in C#


In my previous post, I have shared a simple code to create CSV files and to append data to the same file. In this one, I will share a simple method to read data from a CSV file.

Note: This code will read everything as Strings. But there are so many built-in functions in Visual Studio to convert Strings to any other data type.


 using System;  
 using System.Collections.Generic;  
 using System.ComponentModel;  
 using System.Data;  
 using System.Drawing;  
 using System.Linq;  
 using System.Text;  
 using System.Threading.Tasks;  
 using System.Windows.Forms;  
 namespace WindowsFormsApplication3  
 {  
   public partial class Form1 : Form  
   {  
     public Form1()  
     {  
       InitializeComponent();  
     }  
     private void button1_Click(object sender, EventArgs e)  
     {  
       System.IO.StreamReader reader = new System.IO.StreamReader(System.IO.File.OpenRead(@"D:\WriteData.csv"));  
       while (!reader.EndOfStream)  
       {  
         string line = reader.ReadLine();  
         textBox1.Text += line;  
         textBox1.Text += "\r\n";  
       }  
     }  
   }  
 }  

My Windows Form with a text box and a command button

Once the "Read CSV file" button is pressed, the content will be read line by line, including the commas.