Search code examples
c#filefile-iostreamreaderstreamwriter

Need help editing fields inside of a CSV file?


I'm able to edit each field, however this only works on the first line in the CSV file. If I attempt to input a patient ID that is on the second or third row etc it will not edit any of that data. Anyone know why this is?

I've stored the lines in a string, and then separated them into different fields in another string, used a for loop which I thought would loop through each line until the ID is found.

        {
            string[] fields = lines[i].Split(','); // this here is splitting up each field, so ID,Name, Age will have their own index value

            if (fields[i] == ID) // this is where you will make the change, we need to determine the field here
            {               
                for (int k = 0; k <= fields.Length; k++)
                {
                    if(k == choice)
                    {
                        fields[k-1] = change;
                        Write.WriteLine(fields[0] + "," + fields[1] + "," + fields[2] + "," + fields[3] + "," + fields[4] + "," + fields[5]); // change is made
                    }
                }           
            }
            else
            {
                if (!edited)
                {
                    Write.WriteLine(fields[0] + "," + fields[1] + "," + fields[2]+ "," + fields[3] + "," + fields[4] + "," + fields[5]); // if not edited then it will print the line to the temp file                   
                }
            }                                 
        }
        Write.Close();
        File.Delete("patinfo.csv");
        System.IO.File.Move("temp.csv", "patinfo.csv");                                 
        Console.ReadLine();

Solution

  • if (fields[0] == ID) // replaced i with 0
    {
        for (int k = 1; k <= fields.Length; k++) // replaced 0 with 1
    

    TIP: check 'change', if it is not in [1,6] the row is not written