Skip to main content

CSV string parsing helper in C#.

using System.Collections.Generic;
using System.Text;

namespace Helpers
{
    public static class CsvHelper
    {
        public static List<string> ParseCsv(string record)
        {
            return ParseCsv(record.ToCharArray());
        }

        public static List<string> ParseCsv(IEnumerable<char> record)
        {
            var stringList = new List<string>();
            var flag = false;
            var stringBuilder = new StringBuilder();

            foreach (var ch in record)
            {
                if (ch == '"')
                {
                    flag = !flag;
                }

                if (ch == ',')
                {
                    if (!flag)
                    {
                        stringList.Add(stringBuilder.Replace("\"", string.Empty).ToString());
                        stringBuilder.Remove(0, stringBuilder.Length);
                    }
                    else
                    {
                        stringBuilder.Append(ch);
                    }
                }
                else
                {
                    stringBuilder.Append(ch);
                }
            }

            stringList.Add(stringBuilder.Replace("\"", string.Empty).ToString());

            return stringList;
        }

        public static void AppendValue(StringBuilder output, string value, bool addComma = true)
        {
            if (!string.IsNullOrEmpty(value))
            {
                var stringBuilder = output;
                var str = !value.Contains(",")
                    ? value
                    : string.Format("\"{0}\"", value);

                stringBuilder.Append(str);
            }

            if (!addComma)
            {
                return;
            }

            output.Append(",");
        }

        public static void AppendValue(StringBuilder output, object value, bool addComma = true)
        {
            AppendValue(output, value != null ? value.ToString() : "", addComma);
        }
    }
}