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:
- Changing specific field values to something new i.e., field[3].text = newvalue
- 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???
}
}
question from:
https://stackoverflow.com/questions/65936089/c-sharp-and-csvhelper-how-to-open-file-modify-values-and-re-write-the-file 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…