Features
This code snippet is a function that returns a DataTable by converting a delimited text file. The function also allows for the user to specify if the file’s first row is the column header text.
References
The following namespaces will need to be added in order for the code to compile:
Code
Private Function FileToDataTable(ByVal path As String, ByVal delimiter As Char, ByVal headers As Boolean) As DataTable
Dim dt As New DataTable
Dim lines() As String = IO.File.ReadAllLines(path)
Dim x As Integer = 0
If headers Then
dt.Columns.AddRange((From column As String In lines(x).Split(delimiter) Select New DataColumn(column)).ToArray)
x += 1
Else
dt.Columns.AddRange((From column As String In lines(x).Split(delimiter) Select New DataColumn()).ToArray)
End If
For index As Integer = x To lines.Length - 1
dt.Rows.Add(lines(index).Split(delimiter))
Next
Return dt
End Function
Fiddle: https://dotnetfiddle.net/K5hRbg
Exceptions
If the first row in the text file has less columns than any of the following rows then a System.ArgumentException will be thrown.
If the incorrect delimiter is used then a System.IndexOutOfRangeException will be thrown.
If the file does not exist then a System.IO.FileNotFoundException will be thrown