This code demonstrates how to use the OLE database driver in order to connect to a text file.
using System;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Text;
namespace OLEDBCSVDataSource
{
class CSVDataExample
{
private const string OLE_CONN_STRING = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};" +
"Extended Properties='text;HDR=Yes;FMT=Delimited'";
[STAThread]
static void Main( string[] args )
{
string sFileName = "CSVData.txt";
string sExecPath = Path.GetDirectoryName( System.Reflection.Assembly.GetExecutingAssembly().Location );
string sDataSource = Path.Combine( sExecPath, sFileName );
string sConn = String.Format( OLE_CONN_STRING, sExecPath );
using ( OleDbConnection conn = new OleDbConnection( sConn ) )
{
OleDbCommand cmdSelect = new OleDbCommand( "SELECT * FROM " + sFileName, conn );
conn.Open();
OleDbDataReader reader = cmdSelect.ExecuteReader();
while( reader.Read() )
{
int iFieldCount = reader.FieldCount;
StringBuilder sb = new StringBuilder();
for( int i = 0; i < iFieldCount; i++ )
{
sb.Append( reader.GetValue( i ).ToString() );
sb.Append( "\t" );
}
Console.WriteLine( sb.ToString() );
}
reader.Close();
}
Console.ReadLine();
}
}
}
Comments