Building a Simple CSV Parser in C#




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>

2 comments:

  1. nice one...its working fine

    ReplyDelete
  2. What a great one!! simple but very very nice.
    It helps me a lot!!
    Thank you sooooo much!!!

    ReplyDelete