110,536
社区成员
发帖
与我相关
我的任务
分享
static void Main(string[] args)
{
/*
* 1. Issuse
* Let's say I have 4 fields delimited by tab in each line in the tab-delimited.txt file.
* I also have a schema.ini file in the same folder to indicate the format of the tab-delimited.txt file.
* But it seems the schema.ini file does not override the setting in the system registry(HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Text\Format).
* The text engines can not recognize tab as the delimiter. So it still reads the four fields together into one field.
*
* 2. Solution But Tedious
* Config the default format from CSVDelimited to TabDelimited in HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Jet\4.0\Engines\Text\Format, you will get the expected result.
*/
string dataSourcePath = Environment.CurrentDirectory + "\\";
string dataFileName = "tab-delimited.txt";
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSourcePath + @";Extended Properties=""text;HDR=NO;FMT=TabDelimited""";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = String.Format("SELECT * FROM [{0}]", dataFileName);
DataTable dt = new DataTable(Path.GetFileNameWithoutExtension(dataFileName));
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);
// output as xml.
dt.WriteXml(dataFileName + ".xml");
// output into current console.
Console.WriteLine("The imported data has {0} column(s):", dt.Columns.Count);
foreach (DataColumn col in dt.Columns)
{
Console.Write(col.ColumnName);
Console.Write("\t");
}
Console.WriteLine();
foreach (DataRow row in dt.Rows)
{
foreach (DataColumn col in dt.Columns)
{
Console.Write(row[col]);
Console.Write("\t");
}
Console.WriteLine();
}
Console.WriteLine();
//
Console.Read();
}
修改了一下你的代码,我这里可以看到结果了
string dataSourcePath = @"D:\test";
//string dataFileName = "123.txt";
string connString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dataSourcePath + @";Extended Properties=""text;HDR=NO;FMT=TabDelimited""";
OleDbConnection conn = new OleDbConnection(connString);
OleDbCommand cmd = conn.CreateCommand();
//cmd.CommandText = String.Format("SELECT * FROM text1.txt", dataFileName);
cmd.CommandText = "SELECT * FROM 123.txt";
//DataTable dt = new DataTable(Path.GetFileNameWithoutExtension(dataFileName));
DataTable dt = new DataTable();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(dt);