user3734454
user3734454

Reputation: 59

trying to read one csv file and write to another but it is only writing the last line

I am trying to read information from one csv file and write it to another. when I run the program only the last line is written to the new file

while ((txtline = sr.ReadLine()) != null)   // Reads one line into the variable txtline
{
    //spiliting the file into columns if there is something in it.
   oldcolumns = txtline.Split(',');

   //oldcolumns = Regex.Split(txtline,",");

    //writing the oldcolumns data into the newcolumns.
    newcolumns[0] = oldcolumns[1];
    newcolumns[1] = oldcolumns[0];
    newcolumns[2] = "";
    newcolumns[3] = oldcolumns[3];
    newcolumns[4] = oldcolumns[4];
    newcolumns[5] = "";
    newcolumns[6] = "";

    //using loop to run through all the columns
    csvline = "";
    for (int i = 0; i < 7; i++)
    {
        csvline = csvline + "\"" + newcolumns[i].Replace("\"","") + "\",";
    }
}

//writing to file.
sw.WriteLine(csvline);

Upvotes: 1

Views: 65

Answers (1)

Sergey Berezovskiy
Sergey Berezovskiy

Reputation: 236218

Move sw.WriteLine(csvline) inside while loop:

while ((txtline = sr.ReadLine()) != null) 
{
   ...

   sw.WriteLine(csvline);
}

// currently its here, so it prints only last line after you exit loop

Upvotes: 3

Related Questions