首页 > 解决方案 > C# 和 CsvHelper - 如何打开文件、修改值和重写文件

问题描述

如何使用 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
    }

我已经能够阅读此类的标题和第二行文本,但无法获得正确的语法:

  1. 将特定字段值更改为新值,即 field[3].text = newvalue
  2. 使用 csvWriter 部分重写值。

我已经阅读了示例帮助等,但无法正确引用正在读取的数据。

到目前为止,这有效 - 您可以看到更改值/写入文件问题出现的位置。私人无效按钮1_Click(对象发送者,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???
        }

}

标签: c#csvcsvhelper

解决方案


以下代码有效 - 我不确定在记录集 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);
        }

    }

推荐阅读