How to read a textfile and convert into DataTable?

To read a textfile, convert the contents into Datatable.

1.Use Stream Reader for reading lines of information from a standard text file.
2.Check File Exists or not to avoid IO error.
3.Below code specified the column and rows separation
ex.. In my text file looks like
4. Created temporary 15 columns,assign values after that removed the extra columns
5. if (File.Exists( filePath )){} then retrieve value
6. CreateTable is a function with 3 arguments , 1st arguments is reading text value from textfile , 2nd arguments is to seperate the rows and 3rd arguments is to seperate the columns.

Dim sr As StreamReader = New StreamReader("c:\TestFile2.txt")
Dim str As String = sr.ReadToEnd()
Dim tmptable = CreateTable(str, "|"c, "~"c)

Create Table function

Private Function CreateTable(ByVal strRecords As String, ByVal RowInd As Char, ByVal ColInd As Char) As DataTable

Dim iCount As Integer
Dim iLoop As Integer = 0
Dim jLoop As Integer = 0
Dim sItem As String
Dim sStr() As String, sTemp() As String
Dim tmpDataTable As New DataTable
Const ConstColumn = 15
Dim column As DataColumn
For count = 0 To ConstColumn
column = New DataColumn(count.ToString())

sStr = Split(strRecords, RowInd)
iCount = UBound(sStr)
Dim tmpDataRow As DataRow
For iLoop = 0 To iCount
sItem = sStr(iLoop)
sTemp = Split(sItem, ColInd)
tmpDataRow = tmpDataTable.NewRow()
For jLoop = 0 To UBound(sTemp)
tmpDataRow(jLoop) = sTemp(jLoop)
Dim tm As Int16
For tm = sTemp.Length To ConstColumn
Return tmpDataTable
Catch ex As Exception
Return Nothing
End Try
End Function


No responses found. Be the first to comment...

  • Do not include your name, "with regards" etc in the comment. Write detailed comment, relevant to the topic.
  • No HTML formatting and links to other web sites are allowed.
  • This is a strictly moderated site. Absolutely no spam allowed.
  • Name: