Dealing with commas in a CSV file

后端 未结 27 2763
傲寒
傲寒 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:25

    If you feel like reinventing the wheel, the following may work for you:

    public static IEnumerable SplitCSV(string line)
    {
        var s = new StringBuilder();
        bool escaped = false, inQuotes = false;
        foreach (char c in line)
        {
            if (c == ',' && !inQuotes)
            {
                yield return s.ToString();
                s.Clear();
            }
            else if (c == '\\' && !escaped)
            {
                escaped = true;
            }
            else if (c == '"' && !escaped)
            {
                inQuotes = !inQuotes;
            }
            else
            {
                escaped = false;
                s.Append(c);
            }
        }
        yield return s.ToString();
    }
    

提交回复
热议问题