Search code examples
c#csvcsvhelper

C# and CsvHelper - How to open file, modify values and re-write the file


How can I open a simple 2 line CSV (first line header of 15+ fields, second line data values) using CSVHelper to then modify just some of the values (field 3, 9, 12 for example) and then re-write the file of all 15+ fields

I've created a simple class

    public class InputFileData
    {
        // Match the existing file structure
        public string supplierID { get; set; }
        public string barcode { get; set; }
        public string invoiceNumber { get; set; }
        public string totalCost { get; set; }
        ......rest of fields
    }

I have got as far as being able to read in the header to this class and second line of text but cannot get the syntax right for:

  1. Changing specific field values to something new i.e., field[3].text = newvalue
  2. Using the csvWriter part to re-write the values.

I've read up the sample help etc but cannot reference the data being read in correctly.

This works so far - you can see where the changing value / writing to file question comes up . private void button1_Click(object sender, EventArgs e) {

        inputfileDialog.ShowDialog();

        txtInputFilepath.Text = inputfileDialog.FileName;

        using (var reader = new StreamReader(txtInputFilepath.Text))

        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            // Correctly opens and reads in the header

            var records = csv.GetRecords<InputFileData>();
            
            foreach (var lineOfText in records)
            {
                // Loads up the content on screen so i can see the valus
                txtFileContents.AppendText(lineOfText.authcode_auto + "," + lineOfText.barcode_auto + "," + lineOfText.tagdata_auto + "," + Environment.NewLine);
                
            }

        }

// WRITING BIT

        using (var writer = new StreamWriter("C:\\Users\\Public\\Output2.txt"))

        using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))

        {
            csv.WriteHeader<InputFileData>(); //Correctly writes the header back to the new file
            csv.NextRecord();

            // WHAT TO PUT HERE???
        }

}


Solution

  • The following code works - I'm not sure it's that efficient or correct to be using a seperate list object alongside the record-set IEnumerable but needs must here.... It does ensure regardless of length of file only one row of data is written back which was also needed

    private void button1_Click(object sender, EventArgs e)
        {
            var recordList = new List<InputFileData> { };
            int i = 0;
    
            inputfileDialog.ShowDialog();
    
            txtInputFilepath.Text = inputfileDialog.FileName;
    
            using (var reader = new StreamReader(txtInputFilepath.Text))
    
            using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
    
            {
                recordSet = csv.GetRecords<InputFileData>();
    
                foreach (var lineOfText in recordSet)
                {
                    txtFileContents.AppendText(lineOfText.authcode_auto + "," + lineOfText.barcode + "," + lineOfText.tagdata + "," + Environment.NewLine);
                
                    if (i < 1) { recordList.Add(lineOfText); }; // Reduce text file importing to header and first line of data only
                                                                // Add line to record list 
                    i++;
                }
            }
    
            using (StreamWriter writer = new StreamWriter("C:\\Users\\Public\\Output2.txt"))
    
            using (var csvOut = new CsvWriter(writer, CultureInfo.InvariantCulture))
    
            {
                
            csvOut.WriteHeader<InputFileData>(); //Correctly writes the header back to the new file
            csvOut.NextRecord();
    
            recordList[0].barcode = "TestTestTest";
            recordList[0].suppID = "Test2Test2Test2";
    
            csvOut.WriteRecords(recordList);
            }
    
        }