Programming Course in C# ¡Free!

DBF extractor

 Saturday, April 06, 2013 published by Exercises C#
Proposed exercise

Create a program that displays the list of fields that are stored in a DBF file.

The DBF format is used by the former manager dBase databases, and as an export format supported by many existing tools, such as Excel or Access.

DBF files are divided into two parts: a header that stores information about the file structure and a data area.

The header area is separated from the data area with the CR character (carriage return, ASCII code number 13). At the same time the head is divided into two parts: the first occupies 32 bytes and contains general information about the file, while the second contains information about each field and consists of many blocks of 32 bytes as the table has fields.

The general header file is:

Position Size (bytes) Description

January 1 No. identifies the product in the table was created
Date last update March 2 year / month / day
May 4 of records in the table (in reverse order)
February 9 Total length of the header including CR
February 11 Record length (including the deletion mark character)
February 13 Reserved
January 15 Flag of active Transaction
January 16 Flag of encryption
December 17 indicators for use in local area network
January 29 Flag of file indicated. MDX
March 30 Reserved

The header of each field is:

Position Size (bytes) Description

January 11 Field Name
January 12 Field type (C, D, F, L, M, N)
April 13 Reserved
January 17 Field Length
January 18th decimal number if the numeric field,
   also used for character fields large
February 19 Reserved
January 21 Flag of work area
October 22 Reserved
32 1 Flag of inclusion in the index. MDX

(It can be seen that the number of fields is not indicated in the header, but it can be deduced, knowing the length of the header, that is at positions 9 and 10, and the size of each header block, that is 32 bytes).



using System;
using System.IO;

public class ExtractorDBF
public static void Main()
FileStream fileDBF = File.OpenRead("example.dat"); 
byte [] data = new byte[32];

int amountRead = fileDBF.Read(data,0,32);

if( amountRead != 32 )
size = data[8] + data[9] * 256;      
int numberFields = size / 32 - 1;

for(int i = 0;i < numberFields; i++)
amountRead = fileDBF.Read(data,0,32);

string nameField = "";
for (int j = 0; j < 11; j++)
nameField += Convert.ToChar( data[j] );

Console.WriteLine("Name: {0}",nameField);