Jasinski Technical Wiki

Navigation

Home Page
Index
All Pages

Quick Search
»
Advanced Search »

Contributor Links

Create a new Page
Administration
File Management
Login/Logout
Your Profile

Other Wiki Sections

Software

PoweredBy

Parsing CSV Text - C#

RSS
Modified on Fri, Jan 20, 2017, 9:48 AM by Administrator Categorized as Algorithms, ┬ĚNet Framework

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;
}

ScrewTurn Wiki version 3.0.1.400. Some of the icons created by FamFamFam. Except where noted, all contents Copyright © 1999-2018, Patrick Jasinski.