【问题标题】:How to update the value in a specific column in an existing CSV file using CSVHelper?如何使用 CSVHelper 更新现有 CSV 文件中特定列中的值?
【发布时间】:2021-12-14 16:18:00
【问题描述】:

我有一个 CSV 文件,我在其中添加了我的自动化结果。我可以使用 CSV 帮助器类在文件中添加详细信息。我的要求是一旦执行完成,我的脚本应该更新现有 CSV 文件中的给定列,只是特定列和列值的其余部分应该保持不变。我无法找到相同的解决方案。这是我的 CSV 文件的屏幕截图

执行完成后,我只想更新 ExecutionEndDate 和 ExecutionEndTime 列。其余列不应受到影响。

是否有任何使用 CSV 帮助程序类的解决方案?我尝试了这个问题link 中提供的解决方案,但它也影响了其他列。

感谢任何帮助。

【问题讨论】:

    标签: c# csv csvhelper


    【解决方案1】:

    您应该能够读取其中的记录,将值添加到这两列,然后写回文件。

    void Main()
    {
        List<Foo> records = null;
        
        var csvFile = "SuiteName,ExecutionEnvironment,ExecutionEndDate,ExecutionEndTime,ClientName,SuiteCategory\n";
        csvFile += "Testing_v1,QA,,,XXXX,Regression";
        
        using (var reader = new StringReader(csvFile))
        using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
        {
            records = csv.GetRecords<Foo>().ToList();
        }
        
        records.First().ExecutionEndDate = DateTime.Now.ToShortDateString();
        records.First().ExecutionEndTime = DateTime.Now.ToShortTimeString();
    
        using (var csv = new CsvWriter(Console.Out, CultureInfo.InvariantCulture))
        {
            csv.WriteRecords(records);
        }
    }
    
    public class Foo
    {
        public string SuiteName { get; set; }
        public string ExecutionEnvironment { get; set; }
        public string ExecutionEndDate { get; set; }
        public string ExecutionEndTime { get; set; }
        public string ClientName { get; set; }
        public string SuiteCategory { get; set; }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多