Reading Text File with Multiple Headings in C#

As we know we all deal with different types of reports, maybe its transaction report, balance sheet, income expense statements, etc. All these reports have certain fixed format. Most of the reports have headers for each category of transactions.

table

Now here is the code to fill data table with such type of data and show it in GridView. Later we can fill this data in database.

  1. using System;    
  2.     
  3. using System.Collections.Generic;    
  4. using System.Data;    
  5. using System.IO;    
  6. using System.Linq;    
  7. using System.Web;    
  8. using System.Web.UI;    
  9. using System.Web.UI.WebControls;    
  10.     
  11. public partial class ReadTextFile : System.Web.UI.Page    
  12. {    
  13.     protected void Page_Load(object sender, EventArgs e)    
  14.     {    
  15.     
  16.     }    
  17.     protected void btnRead_Click(object sender, EventArgs e)    
  18.     {    
  19.         gridbind();    
  20.     }    
  21.     protected void gridbind()    
  22.     {    
  23.         DataTable dt = new DataTable();    
  24.         string path = Server.MapPath("~/Marketing.txt");    
  25.         if (!string.IsNullOrEmpty(path))    
  26.         {    
  27.             string[] readText = File.ReadAllLines(path);    
  28.                 
  29.             List<string> rows = readText.ToList<string>();    
  30.               
  31.             DataColumn dc;    
  32.             string [] headers=rows[0].Split(new string[]{ "," },StringSplitOptions.None);    
  33.             foreach (string s in headers)    
  34.             {    
  35.                 dc = new DataColumn(s, typeof(System.String));    
  36.     
  37.                 dt.Columns.Add(dc);    
  38.             }    
  39.             rows.RemoveAt(0);    
  40.             rows.RemoveAll(u => !u.Contains("\""));    
  41.             rows.RemoveAll(u => u.Contains("Totals"));    
  42.             DataRow dr;    
  43.             foreach (string s in rows)    
  44.             {    
  45.                 string[] values = s.Split(new string[] { "\"" }, StringSplitOptions.None);    
  46.                 dr = dt.NewRow();    
  47.                 for (int i = 0; i < headers.Count(); i++)    
  48.                 {    
  49.                     dr[i] = values[i].Replace(",""");    
  50.     
  51.                 }    
  52.                 dt.Rows.Add(dr);    
  53.             }    
  54.         }    
  55.         grdData.DataSource = dt;    
  56.         grdData.DataBind();    
  57.     }    
  58. }