How to properly split a CSV using C# split() function?

前端 未结 6 874
旧时难觅i
旧时难觅i 2020-12-05 19:21

Suppose I have this CSV file :

NAME,ADDRESS,DATE
\"Eko S. Wibowo\", \"Tamanan, Banguntapan, Bantul, DIY\", \"6/27/1979\"

I would like like

6条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 20:09

    Five years old but there is always somebody new who wants to split a CSV.

    If your data is simple and predictable (i.e. never has any special characters like commas, quotes and newlines) then you can do it with split() or regex.

    But to support all the nuances of the CSV format properly without code soup you should really use a library where all the magic has already been figured out. Don't re-invent the wheel (unless you are doing it for fun of course).

    CsvHelper is simple enough to use:

    https://joshclose.github.io/CsvHelper/2.x/

    using (var parser = new CsvParser(textReader)
    {
        while(true)
        {
            string[] line = parser.Read();
    
            if (line != null)
            {
                // do something
            }
            else
            {
                break;
            }
        }
    }
    

    More discussion / same question: Dealing with commas in a CSV file

提交回复
热议问题