The following is a piece of code which I use in my project:
Using Reader As New Microsoft.VisualBasic.FileIO.TextFieldParser(OpenFileDialog1.FileName.ToString())
Reader.TextFieldType = FileIO.FieldType.Delimited
Reader.SetDelimiters("\t")
Dim currentRow As String()
Dim valueArray() As Double = {0, 0, 0, 0}
Dim power3, power2, power1, constVar As Double
power3 = 0.0
power2 = 0.0
power1 = 0.0
constVar = 0.0
While Not Reader.EndOfData
Try
currentRow = Reader.ReadFields()
Dim currentString As String
Dim i As Integer = 0
Dim j As Integer = 0
For Each currentField As String In currentRow
currentString = currentField(0)
MsgBox(currentField)
MsgBox(currentString)
Next
Catch ex As Microsoft.VisualBasic.FileIO.MalformedLineException
MsgBox("Line " & ex.Message & "is not valid and will be skipped.")
End Try
End While
End Using
The text file from which I am reading contains floating point values separated with tabs, like this:
0.5 0.6 0.7 0.8
However, right now, when I run the code, I get the complete line as a string "0.5 0.6 0.7 0.8"
I am having trouble extracting each float value. Please suggest some methods of extracting each value so that i can store them separately.
The TextFieldParser class is supposed to split apart all the fields on each line for you. If it does not do so, it's because you haven't set it up properly. In this case, it looks like your problem is the following line:
Reader.SetDelimiters("\t")
While that kind of string-literal syntax would work in C# and other similar languages, that won't work in VB.NET. The backslash character is not an escape character in VB.NET, so the string is taken exactly as you typed it. So the TextFieldParser is looking for a two-character string consisting of a backslash followed by the letter t rather than a single tab character. If you want to use the tab character as a delimiter, as I strongly suspect is what you intended, then, in VB.NET, you need to do this:
Reader.SetDelimiters(ControlChars.Tab)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With