How to load data from a text/dat file into a data table in c#,Here i need to dynamically generate columns based on the data in a text file.
Asked
Active
Viewed 1,483 times
0
-
Possible duplicate of [How to Read text file to DataTable](http://stackoverflow.com/questions/20860101/how-to-read-text-file-to-datatable) – Draken Jul 11 '16 at 05:42
1 Answers
0
private static System.Data.DataTable SplitColumns()
{
System.Data.DataTable table = new System.Data.DataTable("dataFromFile");
string file="textfile.txt" ==>Get file which you want to split into columns
using (StreamReader sr = new StreamReader(file))
{
string line;
int rowsCount = 0;
while ((line = sr.ReadLine()) != null)
{
string[] data = line.Split(new string[] { "\t"," " }, StringSplitOptions.RemoveEmptyEntries);==>here i'm using the tab delimeter to split the row line
==>in the file to columns data,You can use your own delimeter
if(table.Columns.Count==0)
{
for (int i = 1; i <= data.Length; i++)
{
table.Columns.AddRange(new DataColumn[] { new DataColumn("col"+(i).ToString(), typeof(string)) });==>here i'm dynamically creating the column headers
==> based on the strings in the line
}
}
table.Rows.Add();
for (int i = 0; i < data.Length; i++)
{
if (data[i].Contains(" "))
data[i] = data[i].Replace(" ", "");
if (!data[i].Equals(""))
table.Rows[rowsCount][i] = data[i];
}
rowsCount++;
}
}
return table;
}

Vishnu Babu
- 1,183
- 1
- 13
- 37

Daya giridhar
- 25
- 9
-
1What is this ? Your code that is not working ? If so, you need to post it with the question. – Zein Makki Jul 11 '16 at 05:40
-
-
"Add the following text to a text file and apply the above code" h1 h2 h3 1 2 3 – Daya giridhar Jul 11 '16 at 05:56
-
just try by splitting h1 h2 h3 into one row and 1 2 3 into other row – Daya giridhar Jul 11 '16 at 06:02