Dealing with commas in a CSV file

后端 未结 27 3467
傲寒
傲寒 2020-11-21 06:53

I am looking for suggestions on how to handle a csv file that is being created, then uploaded by our customers, and that may have a comma in a value, like a company name.

27条回答
  •  庸人自扰
    2020-11-21 07:32

        public static IEnumerable LineSplitter(this string line, char 
             separator, char skip = '"')
        {
            var fieldStart = 0;
            for (var i = 0; i < line.Length; i++)
            {
                if (line[i] == separator)
                {
                    yield return line.Substring(fieldStart, i - fieldStart);
                    fieldStart = i + 1;
                }
                else if (i == line.Length - 1)
                {
                    yield return line.Substring(fieldStart, i - fieldStart + 1);
                    fieldStart = i + 1;
                }
    
                if (line[i] == '"')
                    for (i++; i < line.Length && line[i] != skip; i++) { }
            }
    
            if (line[line.Length - 1] == separator)
            {
                yield return string.Empty;
            }
        }
    

提交回复
热议问题