Using OLE to connect to a text file

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();
}
}
}

You might also like...

Comments

Lee Gunn - .NET C# Scotland Lee Gunn is a freelance Microsoft Certified Developer based in Glasgow, Scotland. Specialising in quality driven Internet solutions, largely built around Microsoft’s .NET platform. Skills used o...

Contribute

Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“Programs must be written for people to read, and only incidentally for machines to execute.”