Uzytkownik "markov_alex said:
Hi. In my application i need to read tables that saved as .txt files
with values delimited by ',' into DataTable object. Please tell me
what is good way to do it?
Both those links are broken. Please send me code or another link.
Ok, below is my working example:
a) Data file (E:\myTextData.txt):
b) Test code (OleDb):
using System;
using System.Data;
using System.Data.OleDb;
namespace LoadTextCSharp
{
class Class1
{
static void Main(string[] args)
{
Test t = new Test();
t.LoadData();
t.WriteData();
System.Console.ReadLine();
}
}
class Test
{
//OleDbConnection con = new OleDbConnection("File name=myUdl.udl");
OleDbConnection con = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\;" +
@"Extended Properties=""text;HDR=YES;FMT=Delimited;"";");
OleDbCommand myCom;
DataTable myDt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
public Test()
{
myCom = new OleDbCommand("Select * From myTextData.txt", con);
da.SelectCommand = myCom;
}
public void LoadData()
{
con.Open();
try
{
da.Fill(myDt);
}
catch(OleDbException ex)
{
System.Console.WriteLine(ex.Message);
}
con.Close();
}
public void WriteData()
{
foreach(DataColumn dc in myDt.Columns)
System.Console.Write(dc.ColumnName + "\t");
foreach(DataRow dr in myDt.Rows)
{
System.Console.WriteLine();
foreach(DataColumn dc in myDt.Columns)
System.Console.Write(dr[dc].ToString() + "\t");
}
}
}
}
using System;
using System.Data;
using System.Data.OleDb;
namespace LoadTextCSharp
{
class Class1
{
static void Main(string[] args)
{
Test t = new Test();
//load data from text file
t.LoadData();
//test loaded data
t.WriteData();
System.Console.ReadLine();
}
}
class Test
{
//OleDbConnection con = new OleDbConnection("File name=myUdl.udl");
OleDbConnection con = new OleDbConnection(
@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=E:\;" +
@"Extended Properties=""text;HDR=YES;FMT=Delimited;"";");
OleDbCommand myCom;
DataTable myDt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter();
public Test()
{
myCom = new OleDbCommand("Select * From myTextData.txt", con);
da.SelectCommand = myCom;
}
public void LoadData()
{
con.Open();
try
{
da.Fill(myDt);
}
catch(OleDbException ex)
{
System.Console.WriteLine(ex.Message);
}
con.Close();
}
public void WriteData()
{
foreach(DataColumn dc in myDt.Columns)
System.Console.Write(dc.ColumnName + "\t");
foreach(DataRow dr in myDt.Rows)
{
System.Console.WriteLine();
foreach(DataColumn dc in myDt.Columns)
System.Console.Write(dr[dc].ToString() + "\t");
}
}
}
}
Regards,
Grzegorz