CSV Mangling in VB.NET

Feb 07
2011

I’ll probably go to hell for this one since I imagine there are much better libraries out there to do the right thing, but I needed to write a quick and dirty function in VB.NET to split some quoted CSV into it’s constituent fields.

This is horrible, but it works for the moment.

    'A function to split a quoted comma delimited string into separate fields
    Public Function GetFields(ByVal row As String) As String()
        Dim fields As New List(Of String)
        If row.Length = 0 Then
            Return fields.ToArray()
        End If
 
        Dim current As Integer = 0
        Dim buffer As New StringBuilder()
        Dim betweenQuotes As Boolean = False
        Dim eol As Boolean = False
        While Not eol
 
            Select Case row(current)
                Case CChar("""")
                    betweenQuotes = Not betweenQuotes
 
                Case CChar(",")
                    If betweenQuotes Then
                        buffer.Append(row(current))
                    Else
                        fields.Add(buffer.ToString())
                        buffer = New StringBuilder()
                    End If
 
                Case Else
                    buffer.Append(row(current))
 
            End Select
 
            current += 1
            eol = (current = row.Length)
        End While
 
        'Add the last field
        fields.Add(buffer.ToString())
 
        Return fields.ToArray()
    End Function

NB, you’ll need to add these lines to the top of the file :

Imports System.Text
Imports System.Collections.Generic

Visit Our Friends!

A few highly recommended friends...

Pages List

General info about this blog...