读取DBF文件:System.Data.OleDb.OleDbException

时间:2014-01-21 04:48:55

标签: c# dbf oledbconnection

我正在尝试在C#文件中打开一个DBF并将其上传到MySQL数据库。现在我只是想打开DBF文件,但是我收到以下错误:

A first chance exception of type 'System.Data.OleDb.OleDbException' occurred in System.Data.dll

Error: Failed to retrieve the required data from the DataBase.

Unrecognized database format 'C:\Users\Path\..\..\..\SOMEFILE.DBF'.

我的代码如下。

private void button2_Click(object sender, EventArgs e)
{
    DirectoryInfo dir = new DirectoryInfo(Regex.Replace(textBox1.Text, @"\\", @"\\"));
    foreach (FileInfo file in dir.GetFiles())
    {
        MessageBox.Show(file.Name);
        string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + file.Name;
        string strAccessSelect = "SELECT * FROM "+file.Name.Substring(0,file.Name.Length-4);
        DataSet myDataSet = new DataSet();
        OleDbConnection myAccessConn = null;

        try
        {
            myAccessConn = new OleDbConnection(strAccessConn);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: Failed to create a database connection. \n{0}", ex.Message);
            return;
        }

        try
        {
            OleDbCommand myAccessCommand = new OleDbCommand(strAccessSelect, myAccessConn);
            OleDbDataAdapter myDataAdapter = new OleDbDataAdapter(myAccessCommand);

            myAccessConn.Open();
            myDataAdapter.Fill(myDataSet);
        }
        catch (Exception ex)
        {
            Console.WriteLine("Error: Failed to retrieve the required data from the DataBase.\n{0}", ex.Message);
            return;
        }
        finally
        {
            myAccessConn.Close();
        }
    }
}

我只获得带有文件名的第一个MessageBox,然后抛出错误。

2 个答案:

答案 0 :(得分:3)

您的连接字符串应标识OleDB数据源是DBASE类型:

string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir + ";Extended Properties=dBase III";

另请注意,通过OleDB连接到DBase时,不指定DBF文件,而是指定包含它的文件夹。单个文件是表格。

答案 1 :(得分:1)

使用没有文件名的数据源,只使用路径。

string strAccessConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + dir;