Friday, November 27, 2009

Parsing CSV string using C#

public static string[] SplitCSV(string s)
{
List list = new List();
StringBuilder work = new StringBuilder();
for (int i = 0; i < s.Length; i++)
{
char c = s[i];
if (c == '"')
{
int p2;
while (true)
{
p2 = s.IndexOf('"', i + 1);
work.Append(s.Substring(i + 1, p2 - i - 1));
i = p2;

// If this is a double quote, keep going!
if (((p2 + 1) < s.Length) && (s[p2 + 1] == '"'))
{
work.Append('"');
i++;

// otherwise, this is a single quote, we're done
}
else
{
break;
}
}
}
else if (c == ',')
{
list.Add(work.ToString());
work.Length = 0;
}
else
{
work.Append(c);
}
}
list.Add(work.ToString());
return list.ToArray();
}