This article will show you how to create a simple CSV parser using C# without using any NuGet package. If you want to create an advanced parser in C#, then you can use ANTLR.
What is ANTLR?
As per the ANLTR official website
ANTLR (ANother Tool for Language Recognition) is a powerful parser generator for reading, processing, executing, or translating structured text or binary files.
I have already published one article on that—checkout following tutorial for creating a CSV parser using ANTRL in c#.
Why need CSV Parser?
CSV format is a plain text format in which values are separated by commas (Comma Separated Values) to display or stored the data in the database. We need a parser that reads the data and converts it to C# POCO objects to transfer it to the NoSQL database.
using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.IO;
using System.Collections.Generic;
public partial class ParseCSV : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
List<string[]> testParse =
parseCSV("C:\\TestParse.csv");
DataTable newTable = new DataTable();
foreach (string column in testParse[0])
{
newTable.Columns.Add();
}
foreach (string[] row in testParse)
{
newTable.Rows.Add(row);
}
GridView1.DataSource = newTable;
GridView1.DataBind();
}
public List<string[]> parseCSV(string path)
{
List<string[]> parsedData = new List<string[]>();
using (StreamReader readFile = new StreamReader(path))
{
string line;
string[] row;
while ((line = readFile.ReadLine()) != null)
{
row = line.Split(',');
parsedData.Add(row);
}
}
return parsedData;
}
}
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="ParseCSV.aspx.cs" Inherits="ParseCSV" %>
<!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>Untitled Page</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:GridView ID="GridView1" runat="server">
</asp:GridView>
</div>
</form>
</body>
</html>