How to escape line breaks while creating CSV or TSV file using C#

Hello C# friends.

Are you creating a CSV (Comma Separated Value) or TSV (Tab Separated Value) file in CSharp and you don’t know why your CSV file is breaking when you open it into Excel, then this post is for you.

Mr. Brian has written a very nice article on how to generate CSV file which we referred in our project.
http://www.csharptocsharp.com/generate-csv-from-generic-list

It was difficult to identify the problem. Values in object were html based and we were doing Html.Encode, so i thought that we need to do Html.Decode, but was unlucky.
To get better understanding of Html.Decode and Html.Encode refer: http://www.dotnetperls.com/httputility
Then thought that it can be  Encoding issue so tried to pass different encoding formats to StreamWriter but was unlucky in that too. I tried to identify in depth and reached to the problem and then solution.

Problem:
As my values were in Html format it were containing “t” or “n” or “r” which were creating an issue when writing a file using StreamWriter. As it get “t” or “n” or “r” it was breaking the file.

Read More