0

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.

  • 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 Answers1

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