VB.net code to convert a pipe delimited CSV file to Datatable

Rajnilari2015
Posted by Rajnilari2015 under VB.NET category on | Points: 40 | Views : 322
The below code will do so

Public Shared Function ConvertPipedCSVToDataTable(source As String) As DataTable
Dim dt As New DataTable()
Try
Using stream = New MemoryStream()
Dim input = source
Dim bytes = System.Text.Encoding.[Default].GetBytes(input)
stream.Write(bytes, 0, bytes.Length)
stream.Seek(0, SeekOrigin.Begin)
Using csvReader = New TextFieldParser(stream)
csvReader.SetDelimiters(New String() {"|"})
csvReader.HasFieldsEnclosedInQuotes = True
Dim colFields As String() = csvReader.ReadFields()
For Each column As String In colFields
Dim datecolumn As New DataColumn(column)
datecolumn.AllowDBNull = True
dt.Columns.Add(datecolumn)
Next

While Not csvReader.EndOfData
Dim fieldData As String() = csvReader.ReadFields()
'Making empty value as null
For i As Integer = 0 To fieldData.Length - 1
If fieldData(i) = "" Then
fieldData(i) = Nothing
End If
Next
dt.Rows.Add(fieldData)
End While

Return dt
End Using
End Using

Catch ex As Exception
Throw ex
End Try
End Function

Comments or Responses

Login to post response