I want to append a record to an existing CSV file so the header is already available. I want to just append a new record into existing CVS file.
Following is my code.
string filePath = "C:\Users\dushyant.patel\Desktop\ExportUtility\123.csv";
StreamWriter writer = new StreamWriter(filePath, true);
SharedDataModel model = new SharedDataModel();
model.SrNo = "17";
model.TypeofEvidence = "Video";
var csv = new CsvWriter(writer);
var record = new List
csv.WriteRecords(record);
writer.Close();
return View();
Is there any inbuilt method which I can use?
You would have to read the file then write it again. The reader and writer are forward only. There's no way to edit a file.
You can one file and write to another at the same time though, then delete the old file when done.
Ok. thanks for your valuable response
I have been able to append to a file without repeating the header row:
// Do not include the header row if the file already exists
CsvConfiguration csvConfig = new CsvConfiguration(CultureInfo.CurrentCulture)
{
HasHeaderRecord = !File.Exists(FileName)
};
// WARNING: This will throw an error if the file is open in Excel!
using (FileStream fileStream = new FileStream(FileName, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
{
using (StreamWriter streamWriter = new StreamWriter(fileStream))
{
using (var csv = new CsvWriter(streamWriter, csvConfig))
{
// Append records to csv
csv.WriteRecords(recordsToWrite);
}
}
}
_Note: make sure you build each record in the recordsToWrite collection the same way to avoid column mismatches_
Most helpful comment
I have been able to append to a file without repeating the header row:
_Note: make sure you build each record in the recordsToWrite collection the same way to avoid column mismatches_