Read CSV File into Data Table

In CSV file the first row contains the Headers and other rows contains rest of the data.

Let’s start

  1. Add a web page ReadCSV.aspx after creating new website.
  2. Add a File upload control to choose file.
  3. Add a Submit button read the selected file.
  4. Add a grid view to see the CSV file data.

ReadCSV.aspx

  1. <%@ Page Title="" Language="C#" MasterPageFile="~/Site.master" AutoEventWireup="true" CodeFile="ReadCSV.aspx.cs" Inherits="ReadCSV" %>  
  2.   
  3.     <asp:Content ID="Content1" ContentPlaceHolderID="MainContent" Runat="Server">  
  4.         <asp:Panel ID="PanelMain" runat="server">  
  5.             <br />  
  6.             <table style="width: 44%;">  
  7.                 <tr>  
  8.                     <td style="width: 84px">Select File:</td>  
  9.                     <td style="width: 231px">  
  10.                         <asp:FileUpload ID="FileUpload1" runat="server" />  
  11.                     </td>  
  12.                     <td>  
  13.                         <asp:RequiredFieldValidator ID="RequiredFieldValidator1" runat="server" ErrorMessage="* required" ControlToValidate="FileUpload1" ForeColor="Red" ValidationGroup="validation">  
  14.                         </asp:RequiredFieldValidator>  
  15.                     </td>  
  16.                 </tr>  
  17.                 <tr>  
  18.                     <td style="width: 84px"> </td>  
  19.                     <td style="width: 231px"> </td>  
  20.                 </tr>  
  21.                 <tr>  
  22.                     <td colspan="2">  
  23.                         <asp:Button ID="btnUpload" runat="server" Text="Upload" ValidationGroup="validation" OnClick="btnUpload_Click" />  
  24.                     </td>  
  25.                 </tr>  
  26.             </table>  
  27.             <br />  
  28.             <asp:GridView ID="GridView1" runat="server"></asp:GridView>  
  29.             <br />  
  30.             <asp:Label ID="lblerror" runat="server" />  
  31.         </asp:Panel>  
  32.     </asp:Content>

ReadCSV.aspx.cs

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Data;  
  4. using System.IO;  
  5. using System.Linq;  
  6. using System.Web;  
  7. using System.Web.UI;  
  8. using System.Web.UI.WebControls;  
  9.   
  10. public partial class ReadCSV: System.Web.UI.Page  
  11. {  
  12.     protected void Page_Load(object sender, EventArgs e)  
  13.     {  
  14.   
  15.     }  
  16.   
  17.     protected void btnUpload_Click(object sender, EventArgs e)  
  18.     {  
  19.         try  
  20.         {  
  21.             DataTable dt = new DataTable();  
  22.             dt = ReadCsvFile();  
  23.             GridView1.DataSource = dt;  
  24.             GridView1.DataBind();  
  25.         }  
  26.         catch (Exception ex)  
  27.         {  
  28.             lblerror.Text = ex.Message;  
  29.         }  
  30.     }  
  31.     public DataTable ReadCsvFile()  
  32.     {  
  33.   
  34.         DataTable dtCsv = new DataTable();  
  35.         string Fulltext;  
  36.         if (FileUpload1.HasFile)  
  37.         {  
  38.             string FileSaveWithPath = Server.MapPath("\\Files\\Import" + System.DateTime.Now.ToString("ddMMyyyy_hhmmss") + ".csv");  
  39.             FileUpload1.SaveAs(FileSaveWithPath);  
  40.             using(StreamReader sr = new StreamReader(FileSaveWithPath))  
  41.             {  
  42.                 while (!sr.EndOfStream)  
  43.                 {  
  44.                     Fulltext = sr.ReadToEnd().ToString(); //read full file text  
  45.                     string[] rows = Fulltext.Split('\n'); //split full file text into rows  
  46.                     for (int i = 0; i < rows.Count() - 1; i++)  
  47.                     {  
  48.                         string[] rowValues = rows[i].Split(','); //split each row with comma to get individual values  
  49.                         {  
  50.                             if (i == 0)  
  51.                             {  
  52.                                 for (int j = 0; j < rowValues.Count(); j++)  
  53.                                 {  
  54.                                     dtCsv.Columns.Add(rowValues[j]); //add headers  
  55.                                 }  
  56.                             }  
  57.                             else  
  58.                             {  
  59.                                 DataRow dr = dtCsv.NewRow();  
  60.                                 for (int k = 0; k < rowValues.Count(); k++)  
  61.                                 {  
  62.                                     dr[k] = rowValues[k].ToString();  
  63.                                 }  
  64.                                 dtCsv.Rows.Add(dr); //add other rows  
  65.                             }  
  66.                         }  
  67.                     }  
  68.                 }  
  69.             }  
  70.         }  
  71.         return dtCsv;  
  72.     }  

Let’s discuss the ReadCsvFile() method.

First of all set the location to save the file that is selected by file upload control. I have created a folder named Files to save files.

Using the stream reader read the whole file into a string FullText.

Now split the FullText with ‘\n’ to get the rows (row wise data).

Now split the rows with comma (,) to get the individual values.

After getting individual values add these values into data table by using loops.

table

Now assign the data table to grid view to see the data.