Parsing CSV files in C#, with header

后端 未结 17 1687
悲哀的现实
悲哀的现实 2020-11-21 06:57

Is there a default/official/recommended way to parse CSV files in C#? I don\'t want to roll my own parser.

Also, I\'ve seen instances of people using ODBC/OLE DB to

17条回答
  •  一个人的身影
    2020-11-21 07:13

    Here is my KISS implementation...

    using System;
    using System.Collections.Generic;
    using System.Text;
    
    class CsvParser
    {
        public static List Parse(string line)
        {
            const char escapeChar = '"';
            const char splitChar = ',';
            bool inEscape = false;
            bool priorEscape = false;
    
            List result = new List();
            StringBuilder sb = new StringBuilder();
            for (int i = 0; i < line.Length; i++)
            {
                char c = line[i];
                switch (c)
                {
                    case escapeChar:
                        if (!inEscape)
                            inEscape = true;
                        else
                        {
                            if (!priorEscape)
                            {
                                if (i + 1 < line.Length && line[i + 1] == escapeChar)
                                    priorEscape = true;
                                else
                                    inEscape = false;
                            }
                            else
                            {
                                sb.Append(c);
                                priorEscape = false;
                            }
                        }
                        break;
                    case splitChar:
                        if (inEscape) //if in escape
                            sb.Append(c);
                        else
                        {
                            result.Add(sb.ToString());
                            sb.Length = 0;
                        }
                        break;
                    default:
                        sb.Append(c);
                        break;
                }
            }
    
            if (sb.Length > 0)
                result.Add(sb.ToString());
    
            return result;
        }
    
    }
    

提交回复
热议问题