Search code examples
c#.netdatetime-formatflat-filefilehelpers

FieldConverter ConverterKind.Date not supporting "dd/MM/yyyy HH:mm:ss.ffffff"


I'm trying to read a delimited flat file using file helper library.

[FieldConverter(ConverterKind.Date, "yyyy/MM/dd HH:mm:ss.ffffff")]
public DateTime DateOfInteraction;

But I'm getting the following exception

FileHelpers.ConvertException was unhandled HResult=-2146233088 Message=Error Converting '2015-09-20 23:40:07.707000' to type: 'DateTime'. Using the format: 'yyyy/MM/dd HH:mm:ss.ffffff' Source=FileHelpers ColumnNumber=80 FieldName=DateOfInteraction FieldStringValue=2015-09-20 23:40:07.707000 LineNumber=2 MessageExtra= Using the format: 'yyyy/MM/dd HH:mm:ss.ffffff' MessageOriginal=Error Converting '2015-09-20 23:40:07.707000' to type: 'DateTime'. StackTrace: at FileHelpers.ConvertHelpers.DateTimeConverter.StringToField(String from) at FileHelpers.FieldBase.AssignFromString(ExtractedInfo fieldString, LineInfo line) at FileHelpers.FieldBase.ExtractFieldValue(LineInfo line) at FileHelpers.RecordOperations.StringToRecord(Object record, LineInfo line, Object[] values) at FileHelpers.FileHelperAsyncEngine1.ReadNextRecord() at FileHelpers.FileHelperAsyncEngine1.ReadNext() at FileHelpers.FileHelperAsyncEngine`1.AsyncEnumerator.MoveNext() at TestApplication.Program.Main(String[] args) in c:\MSRS\Old Sys\Practice\CIMStats\TestApplication\Program.cs:line 22 at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args) at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args) at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly() at System.Threading.ThreadHelper.ThreadStart_Context(Object state) at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx) at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state) at System.Threading.ThreadHelper.ThreadStart() InnerException:

I didn't understand why I'm getting the exception even though the date format string is a valid one. The following code snippet giving proper output...

Console.WriteLine("Started: {0:dd/MM/yyyy HH:mm:ss.ffffff}", DateTime.Now);

DateTime format


Solution

  • "/" in a custom date format string is  a culture-specific DateSeparator. So it is being replaced by the date separator for your culture. While converting you have to specify InvariantCulture in culture settings while converting