Source Code: Parse Comma Delimited TextFile with Visual Basic 2005 TextFieldParser
A common question in the Visual Basic forums on the Web is: "How do I parse a comma delimited file?".
For those using Visual Basic 2005, a good solution is the new TextFieldParser class.
The TextFieldParser class provides a way to parse structured text files. A TextFieldParser object can be used to read both delimited and fixed-width files.
The code example below show how to parse a comma delimited text file using a TextFieldParser object.
Code Example
Private Sub LoadCommaDelimetedTextFileIntoListBox(ByVal filePath As String)
' Declare a variable named theTextFieldParser of type TextFieldParser.
Dim theTextFieldParser As TextFieldParser
' Call the My feature's OpenTextFieldParser method passing in a file path.
' Assign the resulting TxtFileParser object to theTextFieldParser variable.
theTextFieldParser = My.Computer.FileSystem.OpenTextFieldParser(filePath)
' Set TextFieldParser object's TextFieldType property to Delimited.
theTextFieldParser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited
' Configure delimiters to handle a comma delimited text file:
' Set TextFieldParser object's Delimiter's property to a string array
' containing one element with the value ",".
theTextFieldParser.Delimiters = New String() {","}
' Declare a variable named currentRow of type string array.
Dim currentRow() As String
' While the end of file has not been reached....
While Not theTextFieldParser.EndOfData
Try
' Read the fields on the current line
' and assign them to the currentRow array variable.
currentRow = theTextFieldParser.ReadFields()
' Declare a variable named currentField of type String.
Dim currentField As String
' Use the currentField variable to loop
' through fields in the currentRow.
For Each currentField In currentRow
' Add the the currentField (a string)
' to the demoLstBox items.
Me.demoListBox.Items.Add(currentField)
Next
Catch malFormLineEx As Microsoft.VisualBasic.FileIO.MalformedLineException
MessageBox.Show("Line " & malFormLineEx.Message & "is not valid and will be skipped.", "Malformed Line Exception")
Catch ex As Exception
MessageBox.Show(ex.Message & " exception has occurred.", "Exception")
Finally
' If successful or if an exception is thrown,
' close the TextFieldParser.
theTextFieldParser.Close()
End Try
End While
Click the link above to download Visual Basic source code in a Visual Studio 2005 solution which demonstrates how to use the TextFieldParser to parse a comma delimited text file and fill a ListBox with the result.
Mike McIntyre http://www.getdotnetcode.com