Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add reading from DBF to DataTable #38

Open
wants to merge 13 commits into
base: master
Choose a base branch
from
43 changes: 43 additions & 0 deletions DotNetDBF/DBFReader.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ original author (javadbf): anil@linuxense.com 2004/03/31
using System.IO;
using System.Text;
using System.Linq;
using System.Data;

namespace DotNetDBF
{
Expand Down Expand Up @@ -57,6 +58,16 @@ public void SetSelectFields(params string[] aParams)
_orderedSelectFields = _selectFields.OrderBy(it => it).ToArray();
}

public void SelectAllFields()
{
List<int> l = new List<int>();
foreach (DBFField f in _header.FieldArray)
l.Add(Array.IndexOf(_header.FieldArray, f));
_selectFields = l.ToArray();
_orderedSelectFields = _selectFields.OrderBy(it => it).ToArray();

}
plmmihail marked this conversation as resolved.
Show resolved Hide resolved

public DBFField[] GetSelectFields()
{
return _selectFields.Any()
Expand Down Expand Up @@ -231,6 +242,38 @@ public object[] NextRecord()
return NextRecord(_selectFields, _orderedSelectFields);
}

/// <summary>
/// Reads the data table from DBF from current position to end.
/// </summary>
/// <returns>The data table with all data, original types and names of columns.</returns>
/// <param name="dataTableName">Name for data table.</param>
public DataTable ReadDataTable(string dataTableName)
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
{
if (_selectFields.Length == 0)
SelectAllFields();
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
DataTable DT = new DataTable(dataTableName);
foreach (int i in _orderedSelectFields)
{
DBFField DF = _header.FieldArray[i];
string n = DF.Name;
DT.Columns.Add(n, DF.Type);
if (DF.Type == typeof(System.String))
DT.Columns[n].MaxLength = DF.FieldLength;
}
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
object[] cDBF = NextRecord(_selectFields, _orderedSelectFields);
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
while (cDBF != null)
{
DataRow nDR = DT.NewRow();
foreach (int i in _orderedSelectFields)
{
nDR[_header.FieldArray[i].Name] = cDBF[i] ?? DBNull.Value;
}
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
DT.Rows.Add(nDR);
cDBF = NextRecord(_selectFields, _orderedSelectFields);
plmmihail marked this conversation as resolved.
Show resolved Hide resolved
}
return DT;
}


internal object[] NextRecord(IEnumerable<int> selectIndexes, IList<int> sortedIndexes)
{
Expand Down