0

My WinForms application reads data from an Excel file to a DataTable. On the first call, everything works as it should. On the second call (15 minutes later, regulated by a System.Timers.Timer), I get the following error at the line conn1.Open();:

External component has thrown an exception

I have searched StackOverflow but have not found anything that quite answers this issue. I have read OleDbConnection gets "External component has thrown an exception.", however that suggests checking the build configuration platform in Visual Studio, which in my case must be correct as the code executes correctly on first calling.

Below is my code:

DataTable dt = new DataTable();
string connectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Mode=Read;Extended Properties=\"Excel 12.0 XML;HDR=Yes\"";
FileInfo file = new FileInfo(path);
OleDbConnection conn1 = new OleDbConnection(connectionString);
conn1.Open(); //Exception is thrown here on second calling
OleDbDataAdapter da = new OleDbDataAdapter(string.Format("SELECT * FROM [Sheet1$]"), conn1);
da.Fill(dt);

The path is always a new file. The old file is replaced by a new file (with a different file name) on every calling.

I have been struggling with this for a few days now, any help is appreciated.

Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
  • 1
    Use a `System.Windows.Forms.Timer` instead. Its `Tick` event is raised in the UI Thread. Not the `System.Timers.Timer` [Elapsed](https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.elapsed) event. Unless you set the [SynchronizingObject](https://learn.microsoft.com/en-us/dotnet/api/system.timers.timer.synchronizingobject). – Jimi Feb 13 '20 at 21:52

1 Answers1

0

Just stripped the code down, line by line, and it turns out that removing the following line makes the code work:

FileInfo file = new FileInfo(path);

If anyone has any suggestions as to why this is the case, I would be interested to know.