Get data in a .dbf file using c# - c#

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.

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

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"]);
}
}

For 64 bit systems I used the Microsoft ACE OLEDB 12.0 data provider, for that provider to work you have to install Microsoft's Access Database Engine 2010
So it looks a lot like the accepted answer but with the provider changed:
string constr = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=c:\folder;Extended Properties=dBASE IV;User ID=Admin;";
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);
}

Related

Update a dbf file with datagridview in C#

Recently my mentor asked me to write a program,manipulating the dbf file in C#.I'm using Odbc & OleDb and now I can read the dbf to datagridview with a dataset.
My question is : how can I input some data in datagridview after reading from the local dbf file and update my input to the local dbf file?
I am new to this, not familiar with relevent APIs so example codes would be a great help.
Here is my code to read the dbf file to datagridvie
string filePath = #"C:\Users\csj\Desktop\db\ZMT.dbf";
FileInfo fi = new FileInfo(filePath);
string mulu = fi.DirectoryName;
string filename = fi.Name;
OleDbConnection conn = new OleDbConnection();
string table = filePath;
string connStr = #"Provider=VFPOLEDB.1;Data Source=" + mulu + ";Collating Sequence=MACHINE";
conn.ConnectionString = connStr;
conn.Open();
string sql = #"select * from " + filename;
OleDbDataAdapter da = new OleDbDataAdapter(sql, conn);
DataSet dt = new DataSet();
da.Fill(dt);
conn.Close(); conn.Dispose();
dataGridView1.DataSource = dt.Tables[0].DefaultView;
Any help?
You should create a OleDbCommandBuilder after you created your OleDbDataAdapter
var builder = new OleDbCommandBuilder(da);
The builder creates Update, Insert and Delete commands for the OleDbDataAdapter.
Then after you made changes in the grid you simply call
da.Update(dt);
That's how it should work ... but I didn't try this for dbfs ...

Missing Required Parameter in Parameterized Query?

I am getting the following error trying to execute the code below
No Value Given For One Or More Required Parameters.
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = "SELECT [FUNCTION],[NAME] from [Sheet1$] WHERE [FUNTION] = ?";
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = connString;
using (OleDbCommand cmd = new OleDbCommand(sql, conn))
{
cmd.Parameters.AddWithValue("?", paraName);
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd);
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
OleDbCommand does not support named parameters (see the docs). What you need to do is something like:
cmd.Parameters.Add(new OleDbParameter { Value = paraName });
Edit: I haven't tried it, but I suppose it might be possible to use your above code and pass null as the name argument...
James, I can see that you are trying to parametrize as you would with SQL. However OleDb wouldn't follow the exact pattern. In OleDb you can simply put question marks in your sql sentence and fill them up later using Parameter.Add().value which is quite straight forward.
As MSDN reference points out:
The OLE DB .NET Provider does not support named parameters for passing
parameters to an SQL statement or a stored procedure called by an
OleDbCommand when CommandType is set to Text.
I have rewritten your code in the way it should look like
string paraName = "CONTROL";
string fullPathToExcel = #"C:\Users\xbbjn2h\Desktop\Mapping.xlsx";
string connString = string.Format(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES;""",fullPathToExcel);
string sql = string.Format("SELECT [{0}],[{1}] from [{2}] WHERE [{0}] = ?", strFunction, strName, strSheetName);
conn.ConnectionString = connString;
using (OleDbConnection conn = new OleDbConnection())
{
OleDbCommand cmd = new OleDbCommand();
cmd.Connection = conn;
cmd.CommandText = sql;
cmd.Parameter.Add("#Param1", OleDbType.VarChar).Value = paraName; // paraName or any value you wish.
DataSet ds = new DataSet();
conn.Open();
OleDbDataAdapter dab = new OleDbDataAdapter(cmd); //or cmd.ExecuteNonQuery(); in Insert sql commands.
dab.Fill(ds);
dataGridView1.DataSource = ds.Tables[0];
conn.Close();
}
Note, You should put your OleDbConnection inside the using statement rather than your OleDbCommand.
I haven't tested it and it may contain some minor error. Other than that punch it there and press play (F5).
You can find more on OleDb parametrization from OleDbCommand.Parameters Property
Good luck and let us know what happens.

How to read excel file which is already open by another user in C#.Net

I have an excel file which is already open by another user. Please help me out how to read it.
I have tried by using following code with READONLY=TRUE in C#, but yet it dint solve my issue.
string stringConExcelMat = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=F:\\PER_Sample\\Input\\6787GHHDSGioSack_v02.xls;Extended Properties=""Excel 8.0;HDR=NO;IMEX=1;READONLY=TRUE""";
DataTable TTable = new DataTable("TABLEMAT");
using (OleDbConnection conn = new OleDbConnection(stringConExcelMat))
{
conn.Open();
using (OleDbDataAdapter da = new OleDbDataAdapter("SELECT * FROM [Raw_Data$A:T]", conn))
{
da.Fill(TTable);
}
}
DataRow RowValues = TTable.Rows[1];

Querying an Excel File from C# - No Results

I have been attempting to query an excel file from C# using an OLEDB connection. There are no runtime errors when the program runs, but it returns no results. I have tried it with different excel files but have gotten a similar result.
edit: The excel file is located in the project directory. If I remove the excel file from the current location the program will get a file not found exception.
private void btnRun_Click(object sender, EventArgs e)
{
string strFileName = "playerData.xls";
string connStr = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + strFileName + ";Extended Properties=" + "\"Excel 8.0;HDR=YES\"";
OleDbConnection conn = new OleDbConnection(connStr);
conn.Open();
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT * FROM [Sheet1$]";
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
DataSet ds = new DataSet();
da.Fill(ds);
dgsResults.DataSource = ds;
conn.Close();
}
Does anyone know why this returns no results?
Thanks,
You are using strFileName in the connStr yet you have not provided the path with it.
Should be along the lines of:
string strFileName = #"c:\excel location\playerData.xls";
Apparently the specific data table has to be referenced in the data binding process. Adding the following line after the fill() method has solved the issue.
da.Fill(ds);
dgsResults.DataSource = ds.Tables[0]; //this is the line to be added

How to read data tables stored in text files (*.rtf, *.doc, *.docx, *.dat) using Odbc?

I have multiple files having data files stored in them.
I want to read them with Odbc or jet engine and stored them into DataSets.
Any ideas how to do that?
I wrote this code but I get error that file is read only:
tring strConnString = #"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dirCSV + #";Extended Properties=""text;HDR=YES;FMT=Delimited""";
OleDbConnection conn = new OleDbConnection(strConnString);
OleDbCommand cmd = conn.CreateCommand();
cmd.CommandText = String.Format("SELECT * FROM [{0}]", fileNevCSV);
DataSet ds2 = new DataSet();
OleDbDataAdapter da = new OleDbDataAdapter(cmd);
da.Fill(ds2);

Categories

Resources