DBF extractor Learn programming with C# Sharp exercises

Lesson:

File Management


Exercise:

DBF extractor 100


Objetive:

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

The DBF format is the one used by the old dBase database manager, and supported as an export format by many current tools, such as Excel or Access.

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

The header zone is separated from the data zone with the character CR (carriage advance, number 13 of the ASCII code). In turn, the header 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 is made up of as many blocks of 32 bytes as fields have the table.

The general header of the file is:

Position Size (bytes) Description

1 1 Nro. that identifies the product with which the table
was created 2 3 Last update date year/month/day
5 4 Total number of records in the table (in reverse order)
9 2 Total length of the header included CR
11 2 Length of registration (includes the character of erase
mark)
13 2 Reserved 15 1 Active
Transaction Flag 16 1 Encryption
flag 17 12 Indicators for local
area network use 29 1 Flag of indica file . MDX
30 3 Reserved

The header of each field is:

Position Size (bytes) Description

1 11 Field
Name 12 1 Field Type (C,D,F,L,M,N)
13 4 Reserved
17 1 Field
Length 18 1 Number of decimal places if the numeric field,also used for large
character fields 19 2 Reserved
21 1 Flag of work
area 22 10 Reserved
32 1 Flag of inclusion in the index . MDX

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


Code:

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)
        {
            Console.WriteLine("Error!!!");
        }
        else
        {
            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);
            }

            fileDBF.Close();
        }
    }
}