0

Is there a way to use FileHelpers without a type? I don't know what comes in the CSV file, I just want to loop through all the cells. I just know that the first row will contain the column names and the others the values.

Thanks

EDIT:

var engine = new DelimitedFileEngine<object>();

But this doesn't work, this gives me the error: The record class Object must be marked with the [DelimitedRecord] or [FixedLengthRecord] Attribute

Timothy
  • 608
  • 3
  • 10
  • 24

3 Answers3

1

Under version 3 there is a way to have file helpers guess the file layout if you look at the examples. You can also read a CSV file as a data table but again thAt expects a class. So my thought is that you would need to combine a few techniques, read the first line to get the header info, parse it to work out how many columns there are and then create an array of that length into columns field and apply type attributes at runtime to the class so that FileHelpers knows what to expect. I think there is a specific array attribute for this but I will have to update my answer later once I get to my PC.

class dynamicArray
{
    public string[] columns;
}

I haven't looked yet whether FileHelpers can utilise the type converter interfaces because if so, you can actually create a dynamic object instead based of an internal dictionary that held the name, type and value of property.

EDIT

Further to this, How can one to dynamically parse a CSV file using C# and the Smart Format Detector in FileHelpers 3.1? has a good answer on how to use the smart detection features. Coupled with your own dictionary or dataset, means you wouldn't need to know what columns where in what order.

Community
  • 1
  • 1
netniV
  • 2,328
  • 1
  • 15
  • 24
0

Use System.Object as type for cells

Alex Lebedev
  • 601
  • 5
  • 14
  • This does not work: Additional information: The record class Object must be marked with the [DelimitedRecord] or [FixedLengthRecord] Attribute engine = new DelimitedFileEngine(); – Timothy Aug 27 '15 at 15:58
0

I ended up using CsvHelper..

var csv = new CsvReader(new StreamReader(file.InputStream));
csv.Configuration.Delimiter = ";";
while (csv.Read())
{
    foreach (string header in csv.FieldHeaders)
    {
       string field = csv.GetField<string>(header);
    }
}
Timothy
  • 608
  • 3
  • 10
  • 24
  • You can actually use TypeDescriptor.AddAttribute to add an attribute at runtime if you really need to. – netniV Sep 03 '15 at 15:05