Question

I have a simple test Windows Forms Application. The first time I run it in VS everything works. If I immediately run it again it throws an exception about read protected memory at adapter.fill(ds); line. If I wait 5 or so minutes the app runs again. I would like some advice from the stackoverflow community on where I am being boneheaded. It is some connection timeout I guess. Code follows:

c#

    public void Button1_Click(object sender, EventArgs e)
    {
        string connectionString = @"Driver={Microsoft dBASE Driver (*.dbf)};DriverID=277;Dbq=x:\CMSBak\ISP;";

        var conn = new OdbcConnection(connectionString);

        conn.Open(); // Open the connection

        string strQuery = "SELECT * FROM ISPINMAS";

        var adapter = new OdbcDataAdapter(strQuery, conn);

        var ds = new DataSet();

        try
        {
            adapter.Fill(ds);
        }
        catch (Exception)
        {
            conn.Close();
            throw;
        }

        DataTable dt = ds.Tables[0];

        dataGridView1.DataSource = dt.DefaultView;

        conn.Close(); // That's it, now close the connection
    }
Was it helpful?

Solution

As usual a disposable object (OdbcConnection) should be disposed when you don't need it anymore.
The using statement will be very helpful in this scenario

    DataSet ds = new DataSet();
    using(OdbcConnection conn = new OdbcConnection(connectionString))
    {
        conn.Open(); // Open the connection
        string strQuery = "SELECT * FROM ISPINMAS";
        var adapter = new OdbcDataAdapter(strQuery, conn);
        adapter.Fill(ds);
    }
    // At this point the connection is closed and dispose has been called to 
    // free the resources used by the connection
    DataTable dt = ds.Tables[0];
    dataGridView1.DataSource = dt.DefaultView;
    // No need to close the connection here

Also note that I have removed from your code the try/catch because you are not trying to handle anything there. You have just closed the connection, but the using statement will ensure that also in case of exceptions.

OTHER TIPS

I found a work around. Use OledB instead and the Microsoft.Jet.OLEDB.4.0 Provider. No more file lock worries.

    string connectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=X:\CMSBak\ISP;Extended Properties=dBASE IV;User ID=Admin;Password=;";
    DataSet ds = new DataSet();
    using(OleDbConnection conn = new OleDbConnection(connectionString))
    {
        conn.Open(); // Open the connection
        string strQuery = "SELECT * FROM ISPINMAS";
        var adapter = new OleDbDataAdapter(strQuery, conn);
        adapter.Fill(ds);
    }
    // At this point the connection is closed and dispose has been called to 
    // free the resources used by the connection
    DataTable dt = ds.Tables[0];
    dataGridView1.DataSource = dt.DefaultView;
    // No need to close the connection here
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top