Thursday, March 7, 2013

Read Data from CSV file and Populate to Dataset



A Function to read CSV file data and populate the data into dataset.

strFolderPath==The path of Source Folder.

strFileName==The Path of the Source File.





Public Function GetCsvData(ByVal strFolderPath As String, ByVal strFileName As String) As DataTable
 
        Dim strConnString As String = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strFolderPath & ";Extended Properties=Text;"
        Dim conn As New OleDbConnection(strConnString)
 
        Try
            conn.Open()
            Dim cmd As New OleDbCommand("SELECT * FROM [" & strFileName & "]", conn)
            Dim da As New OleDbDataAdapter()
 
            da.SelectCommand = cmd
 
            Dim ds As New DataSet()

            da.Fill(ds)
            da.Dispose()

            Return ds.Tables(0)
        Catch
            Return Nothing
        Finally
            conn.Close()
        End Try
 
 End Function