Get data in a .dbf file using c#

China☆狼群 提交于 2019-12-03 19:53:40

问题


How can I get the data in a .dbf file using c#??

What I want to do is to read the data in each row (same column) to further process them.

Thanks.


回答1:


You may create a connection string to dbf file, then using OleDb, you can populate a dataset, something like:

string constr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=directoryPath;Extended Properties=dBASE IV;User ID=Admin;Password=;";
using (OleDbConnection con = new OleDbConnection(constr))
            {
                var sql = "select * from " + fileName;
                OleDbCommand cmd = new OleDbCommand(sql, con);
                con.Open();
                DataSet ds = new DataSet(); ;
                OleDbDataAdapter da = new OleDbDataAdapter(cmd);
                da.Fill(ds);
            }

Later you can use the ds.Tables[0] for further processing.

You may also check this article Load a DBF into a DataTable




回答2:


I found out the accepted answer didn't work for me, as the .dbf files I'm working with are nested in a hierarchy of directories that makes the paths rather long, which, sadly, cause the OleDbCommand object to throw.

I found a neat little library that only needs a file path to work. Here's a little sample adapted from the examples on its GitHub page:

var file = "C:\\Path\\To\\File.dbf";
using (var dbfDataReader = new DbfDataReader(file))
{
    while (dbfDataReader.Read())
    {
        var foo = Convert.ToString(dbfDataReader["FOO"]);
        var bar = Convert.ToInt32(dbfDataReader["BAR"]);
    }
}


来源:https://stackoverflow.com/questions/11356878/get-data-in-a-dbf-file-using-c-sharp

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!