How to detect Column datatype at runtime, while parsing a CSV file with header

风流意气都作罢 提交于 2019-12-08 14:09:28

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!