Skip to content
Tags

,

Simple CSV Parser

December 28, 2011

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

From → C#, Portfolio

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.