Parse or read CSV file using TextFieldParser in ASP.NET

CSV file contains multiple values which are separated by commas (,). In order to parse CSV file, we need to write some code. TextFieldParser class in the Microsoft.VisualBasic.FileIO namespace is used to parse CSV files.
 TextFieldParser reads in CSV files. With it, we specify a delimiter string, and then can read in the fields of every line in a loop.
While parsing CSV file, it doesn’t fetch header row and data rows separately. We need to write some code to fetch first row as a header and remaining as data rows.
Here I’m going to demonstrate how to upload CSV file to the server folder and parse data from that file and bind Gridview.
CSV format in Excel file
We already know that CSV files are comma separated, you may have a question that If a value contains comma then how it’ll parse actual data. The answer is simple, when the values contains comma, it would be quoted.
          First we need to add Reference for Microsoft.VisualBasic. 
          On .NET tab select Microsoft.VisualBasic
 

HTML code:
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
     <div>
    <asp:FileUpload ID="FileUpload1" runat="server" />
    <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="btnSubmit_Click"/>
    </div>
    <div>
        <asp:GridView ID="gvDetails" runat="server">
        </asp:GridView>
    </div>
    </form>
</body>
</html>

Note: 
       Hre you have to add using Microsoft.VisualBasic.FileIO namespace for TextFieldParser class
  
C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Configuration;
using System.IO;
using Microsoft.VisualBasic.FileIO; 
public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void btnSubmit_Click(object sender, EventArgs e)
    {
        if (FileUpload1.HasFile)
        {
            string filename = FileUpload1.FileName.ToString();

            string path = Server.MapPath("~/Document/"+filename);
            FileUpload1.PostedFile.SaveAs(path);
            FetchData(path);
        }
    }

    protected void FetchData(string filepath)
    {
        DataTable dt = new DataTable();
        bool IsFirstRowHeader = true;
        string[] columnf = new string[] { "" };
        using (TextFieldParser parser = new TextFieldParser(filepath))
        {
            parser.TrimWhiteSpace = true;
            parser.TextFieldType = FieldType.Delimited; 
            parser.SetDelimiters(","); 
            if (IsFirstRowHeader)
            {
                columnf = parser.ReadFields(); 
                foreach (string sds in columnf)
                {
                    DataColumn year = new DataColumn(sds.Trim().ToLower(), Type.GetType("System.String"));
                    dt.Columns.Add(year);
                }
            }
            while (true)
            {
                if (IsFirstRowHeader == false)
                {
                    string[] parts = parser.ReadFields(); 
                    if (parts == null)
                    {
                        break;
                    } 
                    dt.Rows.Add(parts);
                }
                IsFirstRowHeader = false;
            }
        } 
        gvDetails.DataSource = dt;
        gvDetails.DataBind();
    } 
}
- See more at: http://www.dotnetfox.com/articles/parse-or-read-csv-file-using-textfieldparser-in-Asp-Net-1112.aspx#sthash.4FhOBaka.dpuf

Comments