Split file .txt to fill in Datatable C#

i need help, i have file txt like below :

Jhonathan   Car   17000
Tony        Bike   4000
Mika        Home  20000

then i want load this file .txt to datatable with split(' '), i do create code like below

DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] aa = File.ReadAllLines(txtFileName);
       foreach (var item in aa)
   {
       DataRow dr = dt.NewRow();
       dr[0] = item.ToString();
       dt.Rows.Add(dr);
   }
   dataGridView3.DataSource = dt;

}

and i hope the result was like below: True Result:

COL1       | COL2   | COL3 
----------------------------     
Jhonathan  | Car    |17000
Tony       | Bike   |4000
Mika       | Home   |20000

but the result from my code not as expected, and the result was like below : Failed Result:

 COL1                   | COL2    | COL3 
-------------------------------------------     
 Jhonathan  Car   17000 |         |
 Tony       Bike  4000  |         |
 Mika       Home  20000 |         |

so how to split for result like true result. Thx :-)

Upvotes: 1

Views: 2643

Answers (2)

Dmitrii Bychenko
Dmitrii Bychenko

Reputation: 186748

I'd rather extract the routine into a method that converts kind of CSV (in your case is tabulation separated file) into table:

private static DataTable FileToTable(String fileName) {
  DataTable result = new DataTable();

  foreach (var line in File.ReadLines(fileName)) {
    DataRow row = result.NewRow();

    //TODO: you may want tabulation ('\t') separator as well as space
    String[] items = line.Split(new Char[] { ' ', '\t' }, StringSplitOptions.RemoveEmptyEntries);
    // Columns adjusting: you don't need exactly 3 columns  
    for (int i = result.Columns.Count; i < items.Length; ++i) 
      result.Columns.Add(String.Format("COL {0}", i + 1));

    row.ItemArray = items;
    result.Rows.Add(row);
  }

  return result;
}

...

dataGridView3.DataSource = FileToTable(txtFileName);

Upvotes: 1

General-Doomer
General-Doomer

Reputation: 2761

Regex solution

// regular expression for split row:
Regex parser = new Regex(@"\s+");

// modified code (replace with your file path)
DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] lines = File.ReadAllLines(@"D:\Temp\text.txt");
foreach (var line in lines)
{
    DataRow dr = dt.NewRow();
    string[] words = parser.Split(line);
    dr[0] = words[0];
    dr[1] = words[1];
    dr[2] = words[2];
    dt.Rows.Add(dr);
}

Fixed string mask solution

// fixed length mask (number of charachers for each field except last field)
int[] mask = { 12, 6 };
int maskLength = mask.Length;

// modified code (replace with your file path)
DataTable dt = new DataTable();
dt.Columns.Add("COL1"); dt.Columns.Add("COL2"); dt.Columns.Add("COL3");
string[] lines = File.ReadAllLines(@"D:\Temp\text.txt");
foreach (var line in lines)
{
    DataRow dr = dt.NewRow();
    int pos = 0;
    for (int i = 0; i < maskLength; pos += mask[i++])
    {
        dr[i] = line.Substring(pos, mask[i]).Trim();
    }
    dr[maskLength] = line.Substring(pos).Trim();
    dt.Rows.Add(dr);
}

Upvotes: 4

Related Questions