Introduction
An article on read text file line by line and split with some delimiter and
bind with Gridview control.
Using the code
First we need to create DataTable
and define its columns.
private DataTable CreateTable()
{
try
{
DataTable table = new DataTable();
DataColumn column;
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Type";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = Type.GetType("System.String");
column.ColumnName = "Time";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Source";
table.Columns.Add(column);
column = new DataColumn();
column.DataType = System.Type.GetType("System.String");
column.ColumnName = "Description";
table.Columns.Add(column);
return table;
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
Next Read Text file line by line and each line split with "[" delimiter. Then
populate DataTable with split data.Paste following code on page load event.
if (!IsPostBack)
{
string OpenPath,contents;
int tabSize = 4;
string[] arInfo;
string line;
DataTable table = CreateTable();
DataRow row;
try
{
OpenPath = Server.MapPath(".") + @"\My File.log";
string FILENAME = OpenPath;
StreamReader objStreamReader;
objStreamReader = File.OpenText(FILENAME);
while ((line = objStreamReader.ReadLine()) != null)
{
contents = line.Replace(("").PadRight(tabSize, ' '), "\t");
char[] textdelimiter = { ']' };
arInfo = contents.Split(textdelimiter);
for (int i = 0; i <= arInfo.Length; i++)
{
row = table.NewRow();
if (i < arInfo.Length)
row["Type"] = arInfo[i].ToString().Replace("[", " ");
if (i + 1 < arInfo.Length)
row["Source"] = arInfo[i + 1].ToString().Replace("[", " ");
if (i + 2 < arInfo.Length)
row["Time"] = arInfo[i + 2].ToString().Substring(1);
if (i + 3 < arInfo.Length)
{
row["Description"] = arInfo[i + 3].ToString().Replace("[", " ");
table.Rows.Add(row);
}
i = i + 2;
}
}
objStreamReader.Close();
GridView1.DataSource = table;
GridView1.DataBind();
}
catch (Exception ex)
{
lblError.Text = ex.Message;
}
}
Kamal Khan works as Software Engineer for about 3 years.In these days i am working on BPM.NET.
BPM.NET 2007 is BPM Workflow software that offers workflow automation and business process modeling capabilities along with full-fledged business activity monitoring (BAM) functions.