我试图用DateTime字段解析记录,但是FileHelpers没有使用我提供的格式。下面是一个应该解析记录但引发错误的F#脚本。我认为这个问题与它是F#脚本有关,因为当我在.fsproj中使用它并与dotnet run一起运行它时,这段代码可以工作。
#r "nuget: FileHelpers, 3.5.1"
open System
open FileHelpers
[<DelimitedRecord(","); IgnoreFirst; CLIMutable>]
type RateRecord =
{
[<FieldConverter(ConverterKind.Date, "yyyy-MM-dd hh:mm")>]
DateTime : DateTime
Value : float
}
let sampleData = """DateTime,Value
2020-02-01 00:00,259
2020-02-01 00:01,267
2020-02-01 00:02,270"""
let engine = FileHelperEngine<RateRecord>()
let values = engine.ReadString sampleData运行脚本的输出。错误消息在末尾。注意,错误消息说它试图使用'ddMMyyyy'格式,这不是我指定的格式。
> #r "nuget: FileHelpers, 3.5.1"
-
- open System
- open FileHelpers
-
- [<DelimitedRecord(","); IgnoreFirst; CLIMutable>]
- type RateRecord =
- {
- [<FieldConverter(ConverterKind.Date, "yyyy-MM-dd hh:mm")>]
- DateTime : DateTime
- Value : float
- }
-
-
- let sampleData = """DateTime,Value
- 2020-02-01 00:00,259
- 2020-02-01 00:01,267
- 2020-02-01 00:02,270"""
-
- let engine = FileHelperEngine<RateRecord>()
- let values = engine.ReadString sampleData
- ;;
[Loading C:\Users\mcrews\AppData\Local\Temp\22000--4251218c-2322-40be-9ae7-fce17ffe54c3\Project.fsproj.fsx]
namespace FSI_0012.Project
FileHelpers.ConvertException: Error Converting '2020-02-01 00:00' to type: 'DateTime'. There are more chars in the Input String than in the Format string: 'ddMMyyyy'
at FileHelpers.Converters.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.FileHelperEngine`1.ReadStreamAsList(TextReader reader, Int32 maxRecords, DataTable dt)
at FileHelpers.FileHelperEngine`1.ReadStream(TextReader reader, Int32 maxRecords)
at FileHelpers.FileHelperEngine`1.ReadString(String source, Int32 maxRecords)
at FileHelpers.FileHelperEngine`1.ReadString(String source)
at <StartupCode$FSI_0013>.$FSI_0013.main@() in d:\Documents\GitHub\Scratchpad\FileHelpers\Test.fsx:line 158
Stopped due to error
>发布于 2022-08-10 21:33:16
看起来,这与F#交互中对F#核心的支持有关。假设您使用的是Visual,如果在Tools > Options中关闭“使用.NET核心脚本”,脚本将按预期工作:

输出:
Microsoft (R) F# Interactive version 12.0.4.0 for F# 6.0
Copyright (c) Microsoft Corporation. All Rights Reserved.
...
val values: RateRecord[] =
[|{ DateTime = 2/1/2020 12:00:00 AM
Value = 259.0 }; { DateTime = 2/1/2020 12:01:00 AM
Value = 267.0 }; { DateTime = 2/1/2020 12:02:00 AM
Value = 270.0 }|]问题是当启用FieldConverter核心脚本时,.NET属性将被忽略。我猜想这在某种程度上是由FileHelpers构建的方式和/或.NET核心脚本中的问题造成的,这导致了反映错误行为(可能是不同版本的.NET之间的组装格式中微妙的不兼容),但我不能肯定。如果我学到更多的话会更新。
https://stackoverflow.com/questions/73310173
复制相似问题