1

Quick question regarding filehelper library:

I have used file helper engine to read stream, do my validation and if the CSV file has not got a header we need to match/map it to my model: i.e

id, name, age, phone, sex, but the CSV might not come in this format/order all the time and we need to match them using a drop down list for each column.

Is there any way I can do this?

Thannks,

DisplayName
  • 71
  • 1
  • 7
  • Quick answer: filehelper is a library and has no GUI. If you want to use drop down lists you'll have to build a GUI yourself using wpf or asp.net, whatever suits you best. – venerik Aug 22 '14 at 13:21
  • already did that, getting those field from json file, i need to get the header now from the CSV file. can i do that in filehelpers? or if they dont have header call the Column1, Column2 ... – DisplayName Aug 22 '14 at 13:26

2 Answers2

1

The short answer, no. BUT you can create a dependent class dynamically:

Since you have the list of possible fields in your JSON file, I would recommend doing a basic System.IO ReadLine for the first data row, and then parse by your delimiter for the individual headers. i.e.:

string headerString;
var headers = new List<String>();

var file = new System.IO.StreamReader("C:\\myFile.txt");
headerString = file.ReadLine();
file.Close();

headers = headerString.Split(',').ToList();

now you have the list of strings for the first row to match against your JSON file. Then you can create your dependent class using System.Reflection.Emit (referenced link below)

typeBuilder.SetParent(typeof(MyFileHelperBaseClass));
// can place the property definitions in a for loop against your headers
foreach(string h in headers){
    typeBuilder.DefineProperty("<header/col#>", ..., typeof(System.Int32), null);
}

stackoverflow article 14724822: How Can I add properties to a class on runtime in C#?

File Helpers gets a little finicky at times, so it will take some tweaking.

Hope this helps

Community
  • 1
  • 1
Eric D
  • 506
  • 3
  • 10
0

You can use File.ReadLines(@"C:\myfile.txt").First() to read the first line and get the headers.

Then you can just use a FileHelpers CodeBuilder to build your runtime class. From the example for a delimited csv file:

DelimitedClassBuilder cb = new DelimitedClassBuilder("Customers", ",");
cb.IgnoreFirstLines = 1;
cb.IgnoreEmptyLines = true;

cb.AddField("BirthDate", typeof(DateTime));
cb.LastField.TrimMode = TrimMode.Both;
cb.LastField.FieldNullValue = DateTime.Today;

cb.AddField("Name", typeof(string));
cb.LastField.FieldQuoted = true;
cb.LastField.QuoteChar = '"';

cb.AddField("Age", typeof(int));

engine = new FileHelperEngine(cb.CreateRecordClass());

DataTable dt = engine.ReadFileAsDT("testCustomers.txt");

Then you can traverse the resulting data table.

shamp00
  • 11,106
  • 4
  • 38
  • 81