4

When using the FileHelpers library I am getting a NullReferenceException when trying to write a .csv file.

I have narrowed the problem down. Whenever I have a null decimal? it throws this exception. It works fine on reading, just not writing.

I have included a sample that shows the same problem as my app:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication11
{
   class Program
   {
      static void Main(string[] args) {
         rec record = new rec { id = 1, mydecimal = null };
         List<rec> records = new List<rec> { record };

         FileHelpers.FileHelperEngine<rec> engine = new FileHelpers.FileHelperEngine<rec>();

         Console.WriteLine(engine.WriteString(records));

      }
   }

   [FileHelpers.DelimitedRecord(",")]
   public class rec
   {
      public int id;
      public decimal? mydecimal;

   }
}
Erick
  • 853
  • 8
  • 17
  • A Nullable should be no problem unless you are on an ancient version of FileHelpers. http://www.filehelpers.com/example_nullable.html – Jonas Elfström Nov 08 '11 at 00:06
  • The version i am using is 2.0.0.0 and comes from nuget. This seems to be the latest version. The code above throws the exception. I have posted the complete project to github, but its just what you see here wrapped in a vs2010 solution/project: https://github.com/estubbs/Stack-overflow-fh-questions – Erick Nov 08 '11 at 16:40

2 Answers2

2

You can use a custom converter.

public class NullableDecimalConverter : FileHelpers.ConverterBase
{
    public override object StringToField(string from)
    {
        return from;
    }

    public override string FieldToString(object fieldValue)
    {
        if (fieldValue == null)
            return String.Empty;
        return fieldValue.ToString();
    }
}

You need to modify your record class to add a [FieldConverter()] attribute to any decimal? field.

[FileHelpers.DelimitedRecord(",")]
public class rec
{
    public int id;

    [FileHelpers.FieldConverter(typeof(NullableDecimalConverter))]
    public decimal? mydecimal;

}
shamp00
  • 11,106
  • 4
  • 38
  • 81
0

Hate to answer my own question, but FileHelpers 2.9.9 fixes this problem. It used to be available on the official site (marked as beta), but can't find it now.

It is however available in NuGet under a package called FileHelpers-stable

Erick
  • 853
  • 8
  • 17