Very simple C# CSV reader

后端 未结 7 1402
渐次进展
渐次进展 2020-11-27 15:08

I\'d like to create an array from a CSV file.

This is about as simple as you can imagine, the CSV file will only ever have one line and these values:



        
相关标签:
7条回答
  • 2020-11-27 16:07

    My solution handles quotes, overriding field and string separators, etc. It is short and sweet.

        public static string[] CSVRowToStringArray(string r, char fieldSep = ',', char stringSep = '\"')
        {
            bool bolQuote = false;
            StringBuilder bld = new StringBuilder();
            List<string> retAry = new List<string>();
    
            foreach (char c in r.ToCharArray())
                if ((c == fieldSep && !bolQuote))
                {
                    retAry.Add(bld.ToString());
                    bld.Clear();
                }
                else
                    if (c == stringSep)
                        bolQuote = !bolQuote;
                    else
                        bld.Append(c);
    
            return retAry.ToArray();
        }
    
    0 讨论(0)
提交回复
热议问题