2

From the CSV spec (RFC 4180), Spaces are considered part of a field and should not be ignored. Obviously if the field contains double quotes it should retain the spaces inside the quotes.

My question is, what about spaces outside of the double quotes? The only way I can see this happening is if the tool that generated the CSV didn't do it properly.

Example: one, "two" ,three

Should the space before and after "two" be included?

2 Answers 2

0

That cell is invalid - to properly code that row it should be:

one," ""two"" ",three

Double quotes must also be escaped (as double-double quote) since they are used as the escape sequence. If you don't want to preserve the quotes around two, technically there are two things invalid about the row - (1) the spaces before and after the quotes and (2) the fact that there are quotes around the cell but nothing to be escaped. CSV demands that there can only be quotes around the cell if there are commas or quotes inside the content of the cell.

If I were in your case, I would err on the side of leniency.

3
  • What I mean is one, "two" ,three, not one," ""two"" ",three. So, it was improperly written. Should it be assumed that the field was improperly written without quotes on the field? Or should it be assumed that the quotes are a part of the quoted field, and there are just spaced before and/or after?
    – Josh Close
    Feb 1, 2011 at 14:56
  • I understand, see my edits. This is a problem with the CSV spec - there are so many variants that we often run into problems between the person who wrote the CSV and the person who's parsing it. (Then I have another huge issue with the fact that you usually have to create a parser from scratch)
    – kelloti
    Feb 1, 2011 at 15:20
  • 1
    Yes, which is what I did. I open-sourced it though, so other people can use it. github.com/JoshClose/CsvHelper It's also available through NuGet.
    – Josh Close
    Feb 16, 2011 at 17:47
0

I dealt with this using BULK INSERT and BCP format files, which is tricky to account for the quote and comma delimiting. In the event that there could be variation, say with a , " delimiter We used the lowest common delimiter, so the comma in your example, then stripped out what wasn't needed like all the double quotes.

But it could also be that your source data was only comma delimited and this was the actual contents of that field. Either way, I would toss out the quotes when loading the field, in whatever method was appropriate.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.