Home » excel » .net 4.0 – what's the proper way to handle multiple connections to multiple Excel files in ADO.NET 4.0?

.net 4.0 – what's the proper way to handle multiple connections to multiple Excel files in ADO.NET 4.0?

Posted by: admin April 5, 2020 Leave a comment

Questions:

I have a piece of code written using VS 2005 that works fine in computers running .NET 2.0 but hard crashes in computers running .NET 4.0.

The section of hte code that’s causing the problem is a call to the DataAdapter’s Fill() method. The code looks as follows:

private void button_Click(object sender, EventArgs e)
{
    DataTable dt1 = new DataTable();
    string connectionString = ... //connects to excelfile1.xls
    string selectCommand = "SELECT * FROM [Sheet1$]";

    using(OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand, connectionString))
    {
        adapter.SelectCommand.Connection.Open();
        adapter.Fill(dt1);
    }

    DataTable dt2 = new DataTable();
    connectionString = ... //connects to excelfile2.xls

    using(OleDbDataAdapter adapter = new OleDbDataAdapter(selectCommand, connectionString))
    {
        adapter.SelectCommand.Connection.Open();
        adapter.Fill(dt2);
    }
}

Several things happen if I make slight modifications to the code:

  1. if I remove the two calls to OleDbConnection.Open(), the code will work just fine with .NET 2.0, but hard crash with .NET 4.0.

  2. if I remove only the second call to OleDbConnection.Open(), the code will work fine with .NET 2.0 and .NET 4.0. Alas, I need to retrieve data from two separate excel files and fill two separate DataTables each time the event is fired.

  3. if I use both calls to OleDbConnection.Open(), as shown in the code above, the code will work fine with .NET 2.0 and .NET 4.0, BUT hard crash with .NET 4.0 the second or third time the user clicks on the button and the procedure runs.

My guess is that .NET 4.0 manages connections differently than .NET 2.0 and I’m missing some very important step.

Can someone please tell how I should write the above code in such a way that it will work fine under .NET 2.0 and .NET 4.0?

How to&Answers:

The problem was “Application Verifier”.