Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / C#

DBF2DataSet

3.46/5 (11 votes)
24 Aug 2007CPOL1 min read 1   1.1K  
An article for converting DBF files to dataset XML files

Introduction

Hello, there. This is my first contribution to The Code Project; I hope you enjoy it. This is a simple project for converting and merging DBF FoxPro files to an XML file, so you can then load it via Dataset.ReadXml(). I did it because I had a lot of DBF files that I wanted to merge and read in an easier way than with VFP.

Background

In this project, I used the concepts below:

  • DbProviderFactory
  • BackgroundWorker

Using the Code

The project consists of a single form with a local DataSet at the form's level. the form reads a default directory in the config file and then loads the DBF files in that directory in a ListBox. This is the code for filling the ListBox with the DBF files:

C#
private void RefrescarDirectorio(string directorio) 
{
    DirectoryInfo d = new DirectoryInfo(directorio);
    FileInfo[] tablas = d.GetFiles("*.dbf");
    // Cargar dbf's de la ruta

    lstTablas.DataSource = tablas;
    lstTablas.DisplayMember = "Name";
}

Then the users can select the DBF files that they want exported, provide a name for the data table and then click Export. This process can be repeated for any DBF files.

Note that if there exists a data table in the DataSet, the program will try to load the data table with the data in the DBF through Datatable.Load(DataReader). No Exception is thrown if the structure of the data table is different from that of the DBFs to merge; that behavior will not be controlled.

This is the code for filling the dataset with the DBFs selected. It is called from within BackgroundWorker.

C#
DbProviderFactory f = DbProviderFactories.GetFactory("System.Data.OleDb");
DbConnection cn = f.CreateConnection();
cn.ConnectionString = 
    "Provider=vfpoledb.1;Data Source=" + txtRutaDbf.Text + 
    ";Collating Sequence=general;";
cn.Open();
foreach (FileInfo fInfo in lstTablas.SelectedItems) 
{
    string archivo = fInfo.Name;
    string comando = "SELECT * FROM " + archivo;
    DbCommand cm = cn.CreateCommand();
    cm.CommandText = comando;
    try 
    {
        dt.Load(cm.ExecuteReader());
    } 
    catch (Exception) 
    {
        //throw;
    }
}

Points of Interest

It's curious to see how the Load and Merge methods of the DataTable object don't take into account the structure of the current table.

History

  • 2007-08-23 First release

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)