I have had a devil of a time trying to figure out how the best way to work with legacy dBASE III database files from C# and .NET. The real trick was to be able to create a new database from within the managed environment. I found several code blocks that showed how to write/read already created databases.
I looked everywhere I could think of but I was not having much luck. My web searching skills are not the best but I feel like I gave it a good effort. I decided to try and do it myself. Below is a class which is the result of my efforts to creating and using dBASE III databases from within C#.NET:
// OLEDbAccess Class - Version 1.00
//
// This class will allow the user to create a new dBase compatible file and manipulate it. It does not allow for reading.
//
// Version 1.00 November 29, 2007 - Initial Release
// Syntax for Create Command
// ————————-
// CREATE TABLE tablename.dbf (fieldname Char(25)
// CREATE TABLE tablename.dbf (fieldname Int)
// Syntax for Insert Command
// ————————-
// INSERT INTO tablename.dbf VALUES(’hi’,1)
using System;
using System.Collections.Generic;
using System.Text;
using System.Data.OleDb;
namespace OLEDbAccess
{
public class OLEDbAccess
{
private string dataSource;
/// <summary>
/// The full path to the folder the dBase tables are located in. DO NOT specify the name of a database.
/// </summary>
public string DataSourcePath
{
get { return dataSource; }
set { dataSource = value; }
}
/// <summary>
/// Use this method to create tables or insert, update, or delete rows from an existing table.
/// </summary>
/// <param name=”modCommand”>The sql string to pass to the method.</param>
/// <returns>Returns true if successful.</returns>
public Boolean DbCommand(string modCommand)
{
if (ModifyTable(OpenDataConnection(), modCommand))
return true;
else
return false;
}
// Open a database base connection via Ole.
private OleDbConnection OpenDataConnection()
{
OleDbConnection conn = null;
try
{
conn = new OleDbConnection(@”Provider=Microsoft.Jet.OLEDB.4.0;Data Source=” + DataSourcePath + “;Extended Properties=DBase III;”);
conn.Open();
return conn;
}
catch (OleDbException odbe)
{
Console.WriteLine(”OleDbException: {0}”, odbe.Message);
return null;
}
}
// Close an existing open Ole database connection.
private void CloseDataConnection(OleDbConnection conn)
{
if (conn.State == System.Data.ConnectionState.Open)
conn.Close();
}
// Non-Query command for database action.
private Boolean ModifyTable(OleDbConnection conn, string modCommand)
{
Boolean success = false;
try
{
OleDbCommand nqcmd = conn.CreateCommand();
nqcmd.CommandText = modCommand;
nqcmd.ExecuteNonQuery();
success = true;
}
catch (OleDbException odbe)
{
Console.WriteLine(”OleDbException: {0}”, odbe.Message);
}
finally
{
CloseDataConnection(conn);
}
return success;
}
}
}
This code serves it purpose well for what I needed it to do. Granted, you can do allot more research and figure out how to completely manipulate dBASE III files but this worked for me.