-1

I am trying to read a csv file using the following code. Its throwing an exception if there is double quotes (") in the data. I want to handle all the special chars while reading.

using (TextReader reader = new StreamReader("C:\\test\test.csv"))
{
    using (CsvReader csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    {
        csv.Read();
        csv.ReadHeader();
        while (csv.Read())
        {
           var result= csv[0].Split(';');
        }
     }
}

My CSV file: The csv.Read is failing line at line# 3

Name;Location;State;Country
Keka1;Lansing; MI; USA
Keka2;"Ohio"; OH; USA  // Error at this line 
Keka3;Lansing; MI; USA

I do not want to escape quotes, but want to include it. Please advice.

aka baka
  • 213
  • 2
  • 10
  • [`TextFieldParser` Class](https://learn.microsoft.com/en-us/dotnet/api/microsoft.visualbasic.fileio.textfieldparser?view=net-6.0) – GSerg May 16 '22 at 20:30
  • 1
    With a CSV library you should not need `Split(';')`. – H H May 16 '22 at 20:46
  • 1
    You need to set `CsvConfiguration.Delimiter = ";"` as shown in [this answer](https://stackoverflow.com/a/66532784/3744182) to [How we can write delimiter like sep=, using CsvHelper library?](https://stackoverflow.com/q/30437440/3744182). Then you should be all set. You will not need to do `csv[0].Split(';');` as the library will split the lines into cells using the specified delimiter. In fact I think this is a duplicate of that question, agree? – dbc May 16 '22 at 20:59
  • 1
    Yes, `var config = new CsvConfiguration(CultureInfo.CurrentCulture) { Delimiter = ";" };` and then `using (var csv = new CsvReader(reader, config))` works, see https://dotnetfiddle.net/SnBQAg. Closing as a duplicate. – dbc May 16 '22 at 21:57

1 Answers1

1

Which CsvReader class are you using? (I authored a class like this called SoftCircuits.CsvParser.)

Either way, you aren't using it correctly. The code you have could just use a regular input stream because you seem to be reading a line at a time and then parsing it. CSV readers will parse it for you and they will handle fields with double quotes.

Jonathan Wood
  • 65,341
  • 71
  • 269
  • 466