Library code snippets

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

Comments

  1. 28 Jan 2006 at 12:30
    Are comma-delimited files the only type supported? If not, how do you specify the delimiter?
  2. 01 Jan 1999 at 00:00

    This thread is for discussions of Using OLE to connect to a text file.

Leave a comment

Sign in or Join us (it's free).

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...
AddThis

We'd love to hear what you think! Submit ideas or give us feedback