Reputation: 11
I want to fill a DataTable with a tab delimited Text file. The text file contains data as follows:
Name Id Place
Sam 2001 USA
Raja 3455 India
Allan 90101 Canada
When I use OleDBConnection
to import the text file into the DataTable, I am getting data in DataTable as follows:
Name_Id_Place
Sam2001USA
Raja3455India
Allan90101Canada
The actual text file has 3 columns and 3 rows, but in the DataTable I got all 3 columns as a single column Name_Id_Place
.
Can anyone tell me the solution for this problem?
Upvotes: 1
Views: 9708
Reputation: 32455
Here I think you reading data from text file in right way, only problem I see that your used Provider cannot understand where a end of column, that why read all row as one column
I had exact same result when trying read data from text file with OleDBConnection.
In my connectionstring as Provider I used:
Provider=Microsoft.Jet.OLEDB.4.0;
If you used same then you need only change "Format" options for this provider in Windows registry:
HKEY_LOCAL_MACHINE \ SOFTWARE \ Microsoft \ Jet \ 4.0 \ Engines \ Text
Then modify "Format" key to value="TabDelimited"
or if you want use some other delimiter character(for example ";") then Format = "Delimited(;)"
Upvotes: 0
Reputation: 20585
static void Main()
{
//create a data table and add the column's
DataTable table = new DataTable("table_name");
table.Columns.Add("name", typeof (String));
table.Columns.Add("id", typeof (Int32));
table.Columns.Add("place", typeof (String));
//start reading the textfile
StreamReader reader = new StreamReader("file_to_read");
string line;
while ((line = reader.ReadLine()) != null)
{
string[] items = line.Split('\t');
//make sure it has 3 items
if (items.Length == 3)
{
DataRow row = table.NewRow();
row["name"] = items[0];
row["id"] = Int32.Parse(items[1]);
row["place"] = items[2];
table.Rows.Add(row);
}
}
reader.Close();
reader.Dispose();
// make use of the table
// when use is done dispose it
table.Dispose();
}
Upvotes: 4