How To Read CSV File In ASP.NET With Example C# and VB.NET

Introduction

In this article, I'll show you, with an example, a way to upload, read/browse and show CSV file (Text File) information in ASP.NET GridView using C# and VB.NET.

CSV file is a computer file that contains Comma Separated (Comma Delimited) Values. The information from a CSV file is browsed and then once the values are separated, a DataTable is created which is able to populate the ASP.NET GridView control. If you want to export datatable to CSV file you can read this article, i not re-posting the same article on c# corner to avoid duplicate content.

HTML Markup

The following HTML Markup consists of an associate ASP.NET FileUpload control, a Button, and a GridView.

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="CS.aspx.cs" Inherits="CS" %>  
  
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">  
<html xmlns="http://www.w3.org/1999/xhtml">  
<head runat="server">  
    <title></title>  
    <style type="text/css">  
        body  
        {  
            font-family: Arial;  
            font-size: 10pt;  
        }  
        table  
        {  
            border: 1px solid #ccc;  
            border-collapse: collapse;  
            background-color: #fff;  
        }  
        table th  
        {  
            background-color: #ff7f00;  
            color: #fff;  
            font-weight: bold;  
        }  
        table th, table td  
        {  
            padding: 5px;  
            border: 1px solid #ccc;  
        }  
        table, table table td  
        {  
            border: 0px solid #ccc;  
        }  
        .button {  
    background-color: #0094ff; /* Blue */  
    border: none;  
    color: white;  
    padding: 15px 32px;  
    text-align: center;  
    text-decoration: none;  
    display: inline-block;  
    font-size: 16px;  
}  
    </style>  
</head>  
<body>  
    <form id="form1" runat="server">  
    <asp:FileUpload ID="FileUpload1"  CssClass="button"  runat="server" />  
    <asp:Button ID="btnImport" CssClass="button" runat="server" Text="Import" OnClick="ImportCSV" />  
    <hr />  
    <asp:GridView ID="GridView1" runat="server">  
    </asp:GridView>  
    </form>  
</body>  
</html>  

Namespaces

For reading the text from CSV file, you need to import the following namespace.

C#

using System.IO;  
using System.Data;  

VB.Net

Imports System.IO  
Imports System.Data  

Upload, Read/browse and show CSV file (Text file) information in ASP.Net GridView

When the Import button is clicked, the CSV file is first uploaded and then saved within a folder named Files. The CSV file information is browsed into a String variable using the File class ReadAllText method.

A DataTable is formed with columns same as that of the destination database table so the CSV file information is split using the new line (\n) and Comma (,) characters. Employing a loop, the information is saved into the DataTable.

Finally, the DataTable is certain to the GridView control.

C#

using System;  
using System.Collections.Generic;  
using System.Linq;  
using System.Web;  
using System.Web.UI;  
using System.Web.UI.WebControls;  
using System.IO;  
using System.Data;  
  
public partial class CS : System.Web.UI.Page  
{  
    protected void ImportCSV(object sender, EventArgs e)  
    {  
        //Upload and save the file  
        string csvPath = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName);  
        FileUpload1.SaveAs(csvPath);  
  
        //Create a DataTable.  
        DataTable dt = new DataTable();  
        dt.Columns.AddRange(new DataColumn[5] { new DataColumn("Id", typeof(int)),  
        new DataColumn("Name", typeof(string)),  
        new DataColumn("Technology", typeof(string)),  
        new DataColumn("Company", typeof(string)),  
        new DataColumn("Country",typeof(string)) });  
  
        //Read the contents of CSV file.  
        string csvData = File.ReadAllText(csvPath);  
  
        //Execute a loop over the rows.  
        foreach (string row in csvData.Split('\n'))  
        {  
            if (!string.IsNullOrEmpty(row))  
            {  
                dt.Rows.Add();  
                int i = 0;  
  
                //Execute a loop over the columns.  
                foreach (string cell in row.Split(','))  
                {  
                    dt.Rows[dt.Rows.Count - 1][i] = cell;  
                    i++;  
                }  
            }  
        }  
  
        //Bind the DataTable.  
        GridView1.DataSource = dt;  
        GridView1.DataBind();  
    }  
}  

VB.Net

Imports System.IO  
Imports System.Data  
  
Partial Class VB  
    Inherits System.Web.UI.Page  
    Protected Sub ImportCSV(sender As Object, e As EventArgs)  
        'Upload and save the file  
        Dim csvPath As String = Server.MapPath("~/Files/") + Path.GetFileName(FileUpload1.PostedFile.FileName)  
        FileUpload1.SaveAs(csvPath)  
  
        'Create a DataTable.  
        Dim dt As New DataTable()  
        dt.Columns.AddRange(New DataColumn(4) {New DataColumn("Id", GetType(Integer)), New DataColumn("Name", GetType(String)), New DataColumn("Technology", GetType(String)), New DataColumn("Company", GetType(String)), New DataColumn("Country", GetType(String))})  
  
        'Read the contents of CSV file.  
        Dim csvData As String = File.ReadAllText(csvPath)  
  
        'Execute a loop over the rows.  
        For Each row As String In csvData.Split(ControlChars.Lf)  
            If Not String.IsNullOrEmpty(row) Then  
                dt.Rows.Add()  
                Dim i As Integer = 0  
  
                'Execute a loop over the columns.  
                For Each cell As String In row.Split(","c)  
                    dt.Rows(dt.Rows.Count - 1)(i) = cell  
                    i += 1  
                Next  
            End If  
        Next  
  
        'Bind the DataTable.  
        GridView1.DataSource = dt  
        GridView1.DataBind()  
    End Sub  
End Class  

Screenshots

CSV File

CSV File

Output


Output

Summary

CSV file is a computer file that contains Comma Separated (Comma Delimited) values. The information from a CSV file is scanned and then, separating the values, a DataTable is created which is able to be accustomed populate the ASP.Net GridView control.