1

I have a C# program that reads in a json file and then spits the contents out to a csv file. The code below uses double quotes to ignore commas within the strings I concatenate together so it does not add extra columns to the csv file. However one of the string values I am reading in contains \n in the middle of it and is creating a new line when I just literally need it to print the entire string including the \n.

This is what I'm using now, it does not work for this issue:

value += @"""" + child.Value.ToString() + @"""" + ",";
Nicole Phillips
  • 753
  • 1
  • 18
  • 41
  • There is absolutely nothing special about "/n" sequence... Are you sure you've put correct sample in the post/title? – Alexei Levenkov Nov 28 '16 at 19:51
  • @Alex I'm not sure what you mean? When writing to the csv file it sees the json string, example: "Here is a sentence with /n inside of it" and cuts to a new line on the csv so Here is a sentence with is on one line and inside is on the next. I need it to remain on one line and ignore the new line shortcut – Nicole Phillips Nov 28 '16 at 19:54
  • Please read [MCVE] guidance to post code that demonstrates the problem. I don't see how `"Here is a sentence with /n inside of it"` would introduce new line and no common Json/CSV libraries replace `"/n"` with new line to my knowledge. – Alexei Levenkov Nov 28 '16 at 19:57
  • 1
    A "\n" is a newline character. I think you have your slashes mixed up. Anyway, you might just try replacing: `child.Value.ToString().Replace("\n", "\\n")` – 001 Nov 28 '16 at 19:57
  • @Johnny I do thanks I'm going to fix that. – Nicole Phillips Nov 28 '16 at 19:59
  • So, the CSV "spec" allows for new lines in values and they appear in the CSV file as ***unencoded*** new lines, but they must be quoted. The start and end of the value are completely delineated by quotation marks, irrespective of how many lines this single value occupies. Yes, this makes a mess of the file when inspecting the contents, but it gets parsed correctly (by Excel, for instance) – spender Nov 28 '16 at 20:03
  • 3
    It would save you a lot of time and incompatibilities if you leveraged an existing CSV library rather than trying to roll your own. This is a solved problem. – spender Nov 28 '16 at 20:05
  • 1
    Possible duplicate of [How do I handle line breaks in a CSV file using C#?](http://stackoverflow.com/questions/1179157/how-do-i-handle-line-breaks-in-a-csv-file-using-c) – dagoltz Nov 28 '16 at 21:10

0 Answers0