Simple CSV Parser
I put together a quick CSV parser that will return a list of strings from a given line. Handles the cases of quoted entries containing both double quotes and commas within the particular cell
public static List<string> SplitCSVLine(string line)
{
var ret = new List<string>();
var quoted = false;
var tokenQuoted = false;
var currentToken = new StringBuilder();
foreach (var c in line)
{
switch (c)
{
case '"':
if (quoted == false && tokenQuoted == false)
{
quoted = true;
tokenQuoted = true;
break;
}
if (quoted && tokenQuoted)
{
quoted = false;
break;
}
if (quoted == false && tokenQuoted)
{
currentToken.Append(c);
quoted = true;
break;
}
break;
case ',':
if (quoted)
{
currentToken.Append(c);
break;
}
ret.Add(currentToken.ToString());
currentToken = new StringBuilder();
tokenQuoted = false;
break;
default:
currentToken.Append(c);
break;
}
}
return ret;
}
Leave a Comment