Code Example: Using TextFieldParser

An example of using the TextFieldParser object

Parsing a delimited string can be tricky. Sometimes there may be multiple delimiters, strings enclosed in quotes with the delimeters inside as well as other complications. The VB.NET TextFieldParser helps simply dealing with these kinds of strings easier.

The TextFieldParser does all the heavy lifting for you. All you really need to tell it are a few simple facts, like which delimiters to use, what to do about quotes and a few other options, and it does the rest.

The function example below is designed to do a split on a delimited string that contains strings in quotes that may or may not contain one of the delimiter characters. You pass in the delimited string and the delimiters and it returns the values in a generic collection List object. You could use a standard String array if you wanted but I've found the generic collection objects to be much better in a number of ways (yes, that will be in another article). In the example, I'm using an in-memory stream. However, you could easily take this code and expand it to using a FileStream instead. Also note the Using statements that help insure that memory is released when the work is done.

 

Public Function QuoteSplit(ByVal parseString As String, ByVal ParamArray Delimiters() As String) As List(Of String)
    Dim Results() As String
    Dim StringEncoding As New ASCIIEncoding()
    Using MemStream As New MemoryStream(StringEncoding.GetBytes(parseString))
        Using Parser As New FileIO.TextFieldParser(MemStream)
            Parser.Delimiters = Delimiters
            Parser.HasFieldsEnclosedInQuotes = True
            Results = Parser.ReadFields()
        End Using
    End Using
    Return New List(Of String)(Results)
End Function

   Save to del.icio.us

© 1999-2007 J. Frank Carr, All Rights Reserved