In this post I will show you how to convert from .csv files to dataset in ASP.NET

Here is the function to convert CSV file to dataset in asp.net using vb.net.
First you need to upload the csv file into your web server, then save the file path.
Add this function code:


    Private Shared Function getCsvToDataset(ByVal strPath As String) As DataSet
        Dim strLine As String
        Dim strArray As String()
        Dim charArray As Char() = New Char() {","c}
        Dim ds As New DataSet()
        Dim dt As DataTable = ds.Tables.Add("TheData")
        Dim aFile As New FileStream(strPath, FileMode.Open)
        Dim sr As New StreamReader(aFile)

        strLine = sr.ReadLine()

        strArray = strLine.Split(charArray)

        For x As Integer = 0 To strArray.GetUpperBound(0)
            dt.Columns.Add(strArray(x).Trim())
        Next

        strLine = sr.ReadLine()
        While strLine IsNot Nothing
            strArray = strLine.Split(charArray)
            Dim dr As DataRow = dt.NewRow()
            For i As Integer = 0 To strArray.GetUpperBound(0)
                dr(i) = strArray(i).Trim()
            Next
            dt.Rows.Add(dr)
            strLine = sr.ReadLine()
        End While
        sr.Close()
        Return ds
    End Function

I think, this is the most effective way to convert csv to dataset. Before this, I already try to use Microsoft.Jet.OLEDB.4.0 but the problem that shows an error message in finding csv file on the web server. So this method using FileStream is the best way.


Share