Parsing CSV Text - C#

Overview

Parsing CSV text can be a challenge when the field values are delimited by double quotes so they can contain commas. Various articles on Stack Overflow recommend the Microsoft.VisualBasic.FileIO.TextFieldParser class, but it doesn't seem to work as advertised. This article suggests a solution using regular expresions, but it doesn't seem to work either. This article provides a simple C# function to parse the text.

Code

private IEnumerable<string> SplitCsvText(string input)
{
    var result = new List<string>();

    var insideQuotes = false;
    var pos1 = 0;

    for (int i = 0; i < input.Length; i++)
    {
        if (input[i] == quote)
        {
            insideQuotes = !insideQuotes;
        }
        else if (input[i] == comma && !insideQuotes)
        {
            var item = input.Substring(pos1, i - pos1).Trim();

            if (item.Length > 0)
                result.Add(item);

            pos1 = i + 1;
        }
    }

    return result;
}