C#从.DBF文件读入数据表

时间:2014-03-12 19:07:14

标签: c# datatable visual-foxpro dbf

我需要使用C#连接到Visual Studio中的.dbf文件并填充数据表。有任何想法吗?我目前可以在Visual Fox Pro 9.0中查看表格

代码我尝试过但失败了,继续

  

外部表格不符合预期格式。

private OleDbConnection conn;
private OleDbCommand cmd;
private OleDbDataReader dr;
private string sqlStr = "";
private DataSet myDataSet;
private OleDbDataAdapter myAdapter;


void test2()
{
    conn = new OleDbConnection(@"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=C:\\Users\\PC1\Documents\\Visual FoxPro Projects\\;Extended Properties=DBASE IV;");
    conn.Open();
    sqlStr = "Select * from Clients.dbf";
    //Make a DataSet object
    myDataSet = new DataSet();
    //Using the OleDbDataAdapter execute the query
    myAdapter = new OleDbDataAdapter(sqlStr, conn);
    //Build the Update and Delete SQL Statements
    OleDbCommandBuilder myBuilder = new OleDbCommandBuilder(myAdapter);         

    //Fill the DataSet with the Table 'bookstock'
    myAdapter.Fill(myDataSet, "somename");
    // Get  a FileStream object
    FileStream myFs = new FileStream
          ("myXmlData.xml", FileMode.OpenOrCreate, FileAccess.Write);
    // Use the WriteXml method of DataSet object to write XML file from the   DataSet
    //  myDs.WriteXml(myFs);
    myFs.Close();
    conn.Close();
}

2 个答案:

答案 0 :(得分:11)

这段代码对我有用!

public DataTable GetYourData()
    {
        DataTable YourResultSet = new DataTable();

        OleDbConnection yourConnectionHandler = new OleDbConnection(
            @"Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\");

        // if including the full dbc (database container) reference, just tack that on
        //      OleDbConnection yourConnectionHandler = new OleDbConnection(
        //          "Provider=VFPOLEDB.1;Data Source=C:\\SomePath\\NameOfYour.dbc;" );


        // Open the connection, and if open successfully, you can try to query it
        yourConnectionHandler.Open();

        if (yourConnectionHandler.State == ConnectionState.Open)
        {
            string mySQL = "select * from CLIENTS";  // dbf table name

            OleDbCommand MyQuery = new OleDbCommand(mySQL, yourConnectionHandler);
            OleDbDataAdapter DA = new OleDbDataAdapter(MyQuery);

            DA.Fill(YourResultSet);

            yourConnectionHandler.Close();
        }

        return YourResultSet;
    }

答案 1 :(得分:0)

Visual FoxPro DBF NOT dBase IV DBF,因此大多数版本的Microsoft Access的Jet数据库引擎都无法读取。 (如果你愿意,MSDN有一些specifics。)

您需要将FoxPro中的DBF导出为实际的dBase格式,或者您需要使用Visual FoxPro OLEDB提供程序将C#打开它。

安装了提供商后,您需要更改"提供商"假设您的DBF在该文件夹中,您的连接字符串的参数为以下内容。

Provider=VFPOLEDB.1;Data Source=C:\Users\PC1\Documents\Visual FoxPro Projects\;

(使用@""字符串格式;您错过了代码示例中的斜杠,在PC1和Documents之间。)