Click here to Skip to main content
14,578,799 members
Rate this:
Please Sign up or sign in to vote.
See more:

I am trying to extract specific columns of data from a text file.

I saw this snippet:

Dim oWrite As System.IO.StreamWriter

oWrite.WriteLine("{0,10}{1,10}{2,25}", "Date", "Time", "Price")

oWrite.WriteLine("{0,10:dd MMMM}{0,10:hh:mm tt}{1,25:C}", Now(), 13455.33)

This code can write data on specific areas of a text file.
I would want to know the opposite, how can i read/extract from a text file on specific areas and put it in an array.

Appreciate the help.
Rate this:
Please Sign up or sign in to vote.

Solution 1

Try the StreamReader.
See here[^].
Rate this:
Please Sign up or sign in to vote.

Solution 2

You'll need to read the different columns within a line, e.g.
if you have 3 columns separated by CHR(9)[Horizontal TAB],
it would be something like this:

Dim tRead As System.IO.StreamReader
Dim Rline, RCol(3), Wline As String
Dim Tlen As Long
Dim m, n, counter, mark(3) As Integer

tRead = IO.File.OpenText(filename)
Do While (tRead.Peek <> -1)
Rline = tRead.ReadLine()
Tlen = Len(Rline)
mark(0) = 0
counter = 1
'Find your separator(s)
For m = 1 To Tlen
  If Mid(Rline, m, 1) = Chr(9) Or Mid(Rline, m, 2) = Chr(13) + Chr(10) Then
    mark(counter) = l
    counter = counter + 1
  End If
Next m
For n = 1 To 3
  RCol(n) = Mid(Rline, mark(n-1)+1, mark(n)-mark(n-1)-1)
Next n
  ' Now do what you want
  DataGridView1.Rows.Add(New Object() {Rcol(1), Rcol(2), Rcol(3)})
  Wline = Rcol(1) + Chr(9) + Rcol(2) + Chr(9) + Rcol(3) + Chr(13) + Chr(10)
  IO.File.AppendAllText(filename2, Wline, System.Text.Encoding.Default)

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100