问题描述
如何使用 CSVHelper 打开一个简单的 2 行 CSV(15 个以上字段的第一行标题,第二行数据值),然后只修改其中的一些值(例如字段 3、9、12),然后重新写入所有 15+ 个字段的文件
我创建了一个简单的类
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
}
我已经能够读取此类的标题和第二行文本,但无法获得正确的语法:
- 将特定字段值更改为新值,即 field[3].text = newvalue
- 使用 csvWriter 部分重写值。
我已经阅读了示例帮助等,但无法正确引用正在读取的数据。
到目前为止,这是有效的 - 您可以看到更改值/写入文件问题出现的位置。 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);
}
}
// 写位
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???
}
}
解决方法
以下代码有效 - 我不确定在记录集 IEnumerable 旁边使用单独的列表对象是否有效或正确,但必须在这里... 它确实确保无论文件长度如何,只写回一行数据,这也是需要的
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);
}
}