How do I handle line breaks in a CSV file using C#?

前端 未结 14 1775
情书的邮戳
情书的邮戳 2020-12-15 08:43

I have an Excel spreadsheet being converted into a CSV file in C#, but am having a problem dealing with line breaks. For instance:

\"John\",\"23\",\"555-555         


        
相关标签:
14条回答
  • 2020-12-15 09:21

    Read the line.
    Split into columns(fields).
    If you have enough columns expected for each line, then process.
    If not, read the next line, and capture the remaining columns until you get what you need.
    Repeat.

    0 讨论(0)
  • 2020-12-15 09:22

    CSV has predefined ways of handling that. This site provides an easy to read explanation of the standard way to handle all the caveats of CSV.

    Nevertheless, there is really no reason to not use a solid, open source library for reading and writing CSV files to avoid making non-standard mistakes. LINQtoCSV is my favorite library for this. It supports reading and writing in a clean and simple way.

    Alternatively, this SO question on CSV libraries will give you the list of the most popular choices.

    0 讨论(0)
  • 2020-12-15 09:27

    Try CsvHelper (a library I maintain). It ignores empty rows. I believe there is a flag you can set in FastCsvReader to have it handle empty rows also.

    0 讨论(0)
  • 2020-12-15 09:29

    Have a look at FileHelpers Library It supports reading\writing CSV with line breaks as well as reading\writing to excel

    0 讨论(0)
  • 2020-12-15 09:35

    Maybe you could count for (") during the ReadLine(). If they are odd, that will raise the flag. You could either ignore those lines, or get the next two and eliminate the first "\n" occurrence of the merge lines.

    0 讨论(0)
  • 2020-12-15 09:37

    You might also check out my CSV parser SoftCircuits.CsvParser on NuGet. It will not only parse a CSV file but--if wanted--can also automatically map column values to your class properties. And it runs nearly four times faster than CsvHelper.

    0 讨论(0)
提交回复
热议问题