views:

179

answers:

2

I'm trying to load a CSV file (delims are ';' and quotes are '"').

I have successfully created everything (the wizard tool is awesome), but there's one thing that I can't find a solution for.

Basically, I have an integer (System.Int32) column. In theory most of the records will have a positive integer value in that column. Sometimes, however, I might encounter a value "N/A" in that column. What I want to achieve, is have FileHelpers assign a default value (-1 works just fine), when it encounters "N/A" in that column.

Does anyone know if this is possible?

PS: I might need to do the same for a System.DateTime field (it might also have "N/A" sometimes).

+4  A: 

The best way that comes to mind to do what you want would be to use the FieldConverter attribute on those fields and create custom converter classes that assign the default value you want the field to have.

You need to create a class that inherits ConverterBase, and then provide implementations for the two virtual methods, StringToField() and FieldToString().

In the FieldToString() method, you'll check to see if the string is equal to "N/A". If it is, return the default value you want.

You will need two different classes, one that can handle Int32 and one that can handle DateTime.

The FileHelpers documentation has an example of how to do this. Link

Brandon Ording
Aha! Exactly what I wanted!
Paulius Maruška
+3  A: 

Like Brandon said u need to use this converter

// In your class
[FieldConverter(typeof(NoValueConverter))]
public int Number;

// Te Converter
public class NoValueConverter : ConverterBase
{
    public override object StringToField(string sourceString)
    {
       if (sourceString.Trim().ToUpper() == "N/A")
        return -1; // or int.MinValue;
       else
        return Integer.Parse(from);
    }

    public override string FieldToString(object fieldValue)
    {
        return fieldValue.ToString();
    }

}

We are glad that u liked the wizard :) (we are working a cool autodetection feature to make it more easy to create the mapping class)

MarcosMeli
since from is a LINQ keyword, should a different parameter name be used, or won't that matter?
Matt Ellen
Your are right Matt :) edited now, thanksMaybe I must to update the sample code of the library that was created for .net 2.0 before from where a reserved keyword.
MarcosMeli