How to use textfieldParser to edit CSV file?

I wrote a small function that reads a csv file using textField, line by line, edit it in a specific field, and write it back to the CSV file.

Here is the code:

private void button2_Click(object sender, EventArgs e)
    {
        String path = @"C:\file.csv";
        String dpath = @"C:\file_processed.csv";
        List<String> lines = new List<String>();

        if (File.Exists(path))
        {
            using (TextFieldParser parser = new TextFieldParser(path))
            {
                String line;

                parser.HasFieldsEnclosedInQuotes = true;
                parser.Delimiters = new string[] { "," };



                while ((line = parser.ReadLine()) != null)
                {
                      string[] parts = parser.ReadFields();

                     if (parts == null)
                     {
                         break;
                     }                   

                          if ((parts[12] != "") && (parts[12] != "0"))
                          {

                              parts[12] = parts[12].Substring(0, 3);
                              //MessageBox.Show(parts[12]);
                          }

                    lines.Add(line);
                }
            }
            using (StreamWriter writer = new StreamWriter(dpath, false))
            {
                foreach (String line in lines)
                    writer.WriteLine(line);
            }
            MessageBox.Show("CSV file successfully processed ! ");
        }
    }

      

The field I want to change is 12th (parts [12]):

for example : if parts[12] = 000,000,234 then change to 000

      

the file is created, the problem is that it does not edit the file and half of the records are missing. I hope someone can point out the error.

+3


source to share


1 answer


You call both parser.ReadFields()

and parser.ReadLine()

. Each of them moves the cursor one by one. This is why you are missing half the lines. Change while

to:

while(!parser.EndOfData)

      

Then add parts = parser.ReadFields();

to the end of the loop. Without it, why you are editing is not visible.

You can also remove:



if (parts == null)
{
    break;
} 

      

Since you no longer have line

, you will need to use fields to track your results:

lines.Add(string.Join(",", parts));//handle string escaping fields if needed.

      

+6


source







All Articles