c# - StreamWriter only writes one line -


i trying write .csv file new file.

every time streamwriter writes, writes first line of new file. overwrites line next string, , continues until streamreader reaches endofstream.
has ever experienced this? how did overcome it?

this first solution outside of required in school work. there unknown number of rows in original file. each row of .csv file has 17 columns. need write 3 of them , in order found in code snippet below.
before coding streamwriter used console.writeline() make sure each line in correct order.

here code snippet:

{     string path = @ "c:\directory\file.csv";     string newpath = @ "c:\directory\newfile.csv"      using(filestream fs = new filestream(path, filemode.open))     {         using(streamreader sr = new streamreader(fs))         {             string line;             string[] columns;             while ((line = sr.readline()) != null)             {                 columns = line.split(',');                 using(filestream afstream = new filestream(                     newpath,                      filemode.openorcreate,                      fileaccess.readwrite))                 using(streamwriter sw = new streamwriter(afstream))                 {                     sw.writeline(columns[13] + ',' + columns[10] + ',' + columns[16]);                     sw.flush();                     sw.writeline(sw.newline);                 }             }         }     } } 

to correctly fix code, you'll want structure more:

public void copyfilecontenttolog() {      var document = readbyline();      writetofile(document); }  public ienumerable<string> readbyline() {      string line;      using(streamreader reader = file.opentext(...))           while ((line = reader.readline()) != null)               yield return line; }  public void writetofile(ienumerable<string> contents) {      using(streamwriter writer = new streamwriter(...))      {           foreach(var line in contents)               writer.writeline(line);            writer.flush();      } } 

you tailor , make bit more flexible. should demonstrate , resolve of issues have loop , streams.


Comments

Popular posts from this blog

php - Permission denied. Laravel linux server -

google bigquery - Delta between query execution time and Java query call to finish -

python - Pandas two dataframes multiplication? -