简体   繁体   English

在运行时配置 FileHelpers DateTimeConverter 格式

[英]Configuring FileHelpers DateTimeConverter format at runtime

I have a need to import a CSV file, but need my users to be able to select the date format their CSV file is using for dates.我需要导入一个 CSV 文件,但需要我的用户能够选择他们的 CSV 文件用于日期的日期格式。

Currently, I have my date property declared as目前,我将我的日期属性声明为

    [FieldOrder(3)]
    [FieldConverter(ConverterKind.Date, "yyyyMMdd")]
    public DateTime contribution_date { get; set; }

However, my client might be uploading a file where the date format is out of their control, and might not be the existing format.但是,我的客户可能正在上传一个日期格式不受他们控制的文件,并且可能不是现有格式。 This throws an exception when I try to parse the file.当我尝试解析文件时,这会引发异常。

Does anybody have a working example of how to change the DateTimeConverter's format (arg1) at runtime?有人有关于如何在运行时更改 DateTimeConverter 格式 (arg1) 的工作示例吗?

My mapped type is a domain object in our EF environment, so I'm hesitant to introduce the ClassBuilder (unless I can start a class builder with an existing class, which I'm not aware I can).我的映射类型是我们 EF 环境中的域对象,因此我对引入 ClassBuilder 犹豫不决(除非我可以使用现有类启动类构建器,但我不知道我可以这样做)。

Any suggestions?有什么建议?

Thanks,谢谢,

Jonathan乔纳森

I ended up using the DelimitedClassBuilder to build a proxy class.我最终使用 DelimitedClassBuilder 来构建一个代理类。 I use this proxy class to map values from a .CSV file into .NET objects, then use reflection to retrieve the values from the object fields and map them onto my desired destination type.我使用这个代理类将值从 .CSV 文件映射到 .NET 对象,然后使用反射从对象字段中检索值并将它们映射到我想要的目标类型。

It seems a little hacky to me, and I'm not 100% certain I'm using the tool as intended.这对我来说似乎有点棘手,我不能 100% 确定我正在按预期使用该工具。

Can anyone confirm that reflection is the expected path for mapping values from these proxy objects?任何人都可以确认反射是从这些代理对象映射值的预期路径吗?

var converter = myEngine.Options.Fields[0].Converter;
var converterType = converter.GetType();
var FieldInfo = converterType.GetField("mFormat", System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.Instance);
FieldInfo.SetValue(converter, myDateFormatString);

That's how I did it, little bit hacky, but it worked!我就是这样做的,有点hacky,但它奏效了!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM