Using net6.0. Using CsvHelper 30.0.1
So when building locally the build succeeds without issue, however when committing to Github the Build fails with the following error:
CsvHelper.TypeConversion.TypeConverterException : The conversion cannot be performed.
Text: '03/20/2023'
MemberName: StartDate
MemberType: System.Nullable`1[[System.DateTime, System.Private.CoreLib, Version=6.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e]]
TypeConverter: 'CsvHelper.TypeConversion.NullableConverter'
IReader state:
ColumnCount: 0
CurrentIndex: 2
HeaderRecord:
["Id","Name","StartDate","TotalSpend"]
IParser state:
ByteCount: 0
CharCount: 56
Row: 2
RawRow: 2
Count: 4
RawRecord:
1,Test name,03/20/2023,0.12
Here is the code: `
public class CsvProcessingServiceTests
{
public void GetCsvStreamAsTransactionTypeTest()
{
var testObject = new CsvProcessingServiceTestObject
{
Id = 1,
Name = "Test name",
StartDate = DateTime.ParseExact("2023-03-20", "yyyy-MM-dd",
CultureInfo.GetCultureInfo("en-GB")),
TotalSpend = (decimal?)0.12
};
var testObjectInput = testObject.GetCSV();
var testStream = new MemoryStream(Encoding.UTF8.GetBytes(testObjectInput));
var result = _csvProcessingService.GetCsvStreamAsTransactionType<CsvProcessingServiceTestObject>(new StreamReader(testStream));
}
private class CsvProcessingServiceTestObject
{
public string GetCSV()
{
var objectAsString = new StringBuilder();
objectAsString.Append("Id,Name,StartDate,TotalSpend\n");
objectAsString.Append($"{Id},{Name},{StartDate?.Date.ToString("d")},{TotalSpend}");
return objectAsString.ToString();
}
public int? Id { get; set; }
public string? Name { get; set; }
public DateOnly? StartDate { get; set; }
public decimal? TotalSpend { get; set; }
}
}
public class CsvProcessingService {
private readonly CsvConfiguration _csvConfiguration;
public CsvProcessingService()
{
_csvConfiguration = new CsvConfiguration(CultureInfo.GetCultureInfo("en-GB"))
{
TrimOptions = TrimOptions.Trim,
HeaderValidated = null,
MissingFieldFound = null
};
}
public List<T> GetCsvStreamAsTransactionType<T>(StreamReader inputStreamReader)
{
using var sr = new StreamReader(inputStreamReader);
using var csv = new CsvReader(sr, _csvConfiguration);
var csvRecords = csv.GetRecords<T>().ToList();
return csvRecords;
}
}
`
Anyone have any ideas? I changed the (StartDate) DateTime to DateOnly but that also seemed to fail. It only seems to work when StartDate is set to a string. Is there an issue with the GitHub Build? Why does it work when running locally in VS but not when commited to GitHub?
CodePudding user response:
Try changing your GetCsv
to provide culture info for StartDate?.Date.ToString
:
objectAsString.Append($"{Id},{Name},{StartDate?.Date.ToString("d", CultureInfo.GetCultureInfo("en-GB"))},{TotalSpend}");
en-Gb
should process dates as day–month–year while 03/20/2023
(value from error) obviously is not.
Or just use fixed custom formatting and do not rely on culture and standard formats.