I have implemented a code to upload and get data from an excel file and put it in a DataTable. The code usually works fine, but sometimes I get the following exception when the method da.Fill(dt) is being called: External component has thrown an exception.
Below the code I implemented:
Protected Sub upload_button_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles upload_button.Click
If Not (File1.PostedFile Is Nothing) Then
Dim filename As String = getFileName(File1.PostedFile.FileName)
Try
If filename = "" Then
uploadError.Visible = True
Else
uploadError.Visible = False
Dim filepath As String = savePath & filename
Dim fileExtension = Path.GetExtension(filepath)
If fileExtension.ToLower <> ".xls" And fileExtension.ToLower <> ".xlsx" Then
uploadError.Text = "The file must have an excel type"
uploadError.Visible = True
successUpload.Visible = False
Else
Dim postedFile = File1.PostedFile
postedFile.SaveAs(filepath)
While Not System.IO.File.Exists(filepath)
Thread.Sleep(1000)
End While
Dim constring = String.Format("Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties=""Excel 12.0 Xml;HDR=YES""", filepath)
Dim dt As New DataTable
Dim con = New OleDbConnection(constring)
Dim da = New OleDbDataAdapter("select * from [Sheet1$]", con)
da.Fill(dt)
End If
End If
Catch ex As InvalidOperationException
Throw ex
Catch ex As SystemException
Throw ex
Catch ex As Exception
Throw ex
End Try
End If
End Sub
Could you help me to identify the cause of the exception and resolve it?
Thank you in advance