Naseem
Naseem

Reputation: 961

How to update the value in a specific column in an existing CSV file using CSVHelper?

I have a CSV file in which I am adding the result of my automation result. I am able to add the details in the file using the CSV helper class. My requirement is once the execution is done, my script should update the given column in an existing CSV file, just the specific column and rest of the column value should remain the same. I am unable to find the solution for the same. Here is the screenshot of my CSV file

enter image description here

Once the execution is done, I want to just update the ExecutionEndDate and ExecutionEndTime columns. The remaining column should not be impacted.

Is there any solution for the same using CSV helper class? I tried the solution provided in this question link but it is impacting the other columns as well.

Any help is appreciated.

Upvotes: 0

Views: 1343

Answers (1)

David Specht
David Specht

Reputation: 9074

You should be able to read the records in, add values to those two columns and then write back to the file.

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; }
}

Upvotes: 1

Related Questions