Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I handle line breaks in a CSV file using C#?
    text
    copied!<p>I have an Excel spreadsheet being converted into a CSV file in C#, but am having a problem dealing with line breaks. For instance:</p> <pre><code>"John","23","555-5555" "Peter","24","555-5 555" "Mary,"21","555-5555" </code></pre> <p>When I read the CSV file, if the record does not starts with a double quote (") then a line break is there by mistake and I have to remove it. I have some CSV reader classes from the internet but I am concerned that they will fail on the line breaks.</p> <p>How should I handle these line breaks?</p> <hr> <p>Thanks everybody very much for your help.</p> <p>heres is what ive done so far, my records have fixed format and all start with </p> <pre><code>JTW;...;....;...; JTW;...;...;.... JTW;....;...;.. ..;...;... (wrong record, line brak inserted) JTW;...;... </code></pre> <p>so i checked for the <code>;</code> in the [3] position of each line. if true i write, if false ill append on the last *removing the line-break)</p> <p>Im having problems now because im saving the file as a txt. </p> <p>By the way, i am converting the excell spreadshit to csv by saving as csv in excell. but im not sure if the client is doing that.</p> <p>So the file as a TXT is perfect. ive checked the records and totals. But now i have to convert it back to csv and i would really like to do it in the program. Does anybody know how ? </p> <p>here is my code:</p> <pre><code>namespace EditorCSV { class Program { static void Main(string[] args) { ReadFromFile("c:\\source.csv"); } static void ReadFromFile(string filename) { StreamReader SR; StreamWriter SW; SW = File.CreateText("c:\\target.csv"); string S; char C='a'; int i=0; SR=File.OpenText(filename); S=SR.ReadLine(); SW.Write(S); S = SR.ReadLine(); while(S!=null) { try { C = S[3]; } catch (IndexOutOfRangeException exception){ bool t = false; while (t == false) { t = true; S = SR.ReadLine(); try { C = S[3]; } catch (IndexOutOfRangeException ex) { S = SR.ReadLine(); t = false; } } } if( C.Equals(';')) { SW.Write("\r\n" + S); i = i + 1; } else { SW.Write(S); } S=SR.ReadLine(); } SR.Close(); SW.Close(); Console.WriteLine("Records Processed: " + i.ToString() + " ."); Console.WriteLine("File Created SucacessFully"); Console.ReadKey(); } } } </code></pre>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload