I am using CsvHelper library to write to a CSV file. However, some of my CSV files have varying encodings, causing random characters to appear in the written data. Below is a code sample illustrating how I am currently handling this in my project. How could I solve it?
public async Task WriteAsync<T>(string path, T record)
{
bool containsNewLines = ContainsNewLines(path);
using (var stream = File.Open(path, FileMode.Append))
using (var writer = new StreamWriter(stream, Encoding.UTF8))
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
if (!containsNewLines)
{
await csv.NextRecordAsync();
}
csv.WriteRecord(record);
await csv.NextRecordAsync();
}
}
private bool ContainsNewLines(string filePath)
{
using (var reader = new StreamReader(filePath))
{
string content = reader.ReadToEnd();
return content.EndsWith(Environment.NewLine);
}
}