Obtener columnas archivo DBF desde C Sharp

A continuación les traigo una función muy útil que les permitirá obtener un DataTable con los datos de las columnas de un DBF.


public static DataTable estructuraDBF(string file)
{
  const int BLOCK_SIZE = 32;
  const int NAME_LENGTH = 10;
  int numOfField;
  int amountRead;
  int headerSize;
  byte[] data = new byte[BLOCK_SIZE];
  byte[] aux = new byte[1];
  DataTable dt = new DataTable();
  FileStream input = File.OpenRead(file);

  dt.Columns.Add("FIELDNAME", typeof(String));
  dt.Columns.Add("TYPE", typeof(String));
  dt.Columns.Add("LENGTH", typeof(int));
  dt.Columns.Add("DECIMALS", typeof(int));
            
  // Leer encabezado archivo
  amountRead = input.Read(data, 0, BLOCK_SIZE);
            
  if (amountRead != BLOCK_SIZE)
  {
     input.Close();
     return dt;
  }
  // Numero de campos

  headerSize = data[8] + data[9] * 256;
  numOfField = headerSize / BLOCK_SIZE - 1;
           
  for (int i = 0; i < numOfField; i++)
  {
     int j = 0;
     string awAux = "";

     awAux = "";
     while ((Convert.ToInt32(data[j]) >= 32) &&
            (Convert.ToInt32(data[j]) <= 127) && (j <= NAME_LENGTH))
     {
       awAux = awAux + Convert.ToChar(data[j]);
       j++;
     }

     if (!awAux.Equals(""))
     {
       dt.Rows.Add();
       amountRead = input.Read(data, 0, BLOCK_SIZE);

       dt.Rows[i][0] = System.Text.Encoding.ASCII.GetString(data, 0, NAME_LENGTH).Trim('\0');
       dt.Rows[i][1] = System.Text.Encoding.ASCII.GetString(data, 11, 1);
       aux[0] = data[16];
       dt.Rows[i][2] = (int)aux[0];
       aux[0] = data[17];
       dt.Rows[i][3] = (int)aux[0];
       if (dt.Rows[i][0].Equals(""))
       {
          dt.Rows.Remove(dt.Rows[i]);
       }
     }
                
   }
   dt.Rows.RemoveAt(dt.Rows.Count - 1);
   return dt;
}

El resultado será un data table:

FIELDNAME TYPE LENGTH DECIMALS
NOMBRE C 50 0
RUT C 20 0

También te podría gustar...

Deja una respuesta

Tu dirección de correo electrónico no será publicada.