问题
I am using FileHelpers to load CSV data, (credit - while searching found this answer/search result).
The user browses a dir., selects the files with headers, and uploads for parsing. My issues is that -- they are one time files, whose cols/classes/types are not known previously.
Question: how can I detect the column's datatype while parsing?
After searching I found a function called public Type
RecordType { get; }
it provides the record type.. I need help to get the Col data type in the record.
var fNengine = new FileHelperEngine<AttendeeEventManifesto>();
var fNrecords = engine.ReadFile("AttendeesByEvents.csv");
// How to get the Col types?
// HeaderText = typeof(..*notKNown*).GetCsvHeader();
//..var headers = fNrecords.HeaderText();
//foreach (var header in headers)
// Console.WriteLine(header.RecordType() + `\n`);
I also found this answer on SO, but the runtime helpers mentioned by @shmap00 or the help he is referring to is no longer there, i looked in the source tree as well. Can some one point me to the link please
回答1:
You can use a class builder to build your class at runtime like this:
DelimitedClassBuilder cb = new DelimitedClassBuilder("MyProduct", delimiter: ",");
cb.AddField("Name", typeof(string));
cb.LastField.TrimMode = TrimMode.Both;
cb.AddField("Description", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';
cb.LastField.QuoteMode = QuoteMode.OptionalForBoth;
// etc... e.g., add a date field
cb.AddField("SomeDate", typeof(DateTime));
engine = new FileHelperEngine(cb.CreateRecordClass());
DataTable dt = engine.ReadFileAsDT("test.txt");
来源:https://stackoverflow.com/questions/53136232/how-to-detect-column-datatype-at-runtime-while-parsing-a-csv-file-with-header